首页 > 试题广场 >

修改程序清单11.5,使之将一系列连续的随机漫步者位置写入到

[问答题]
修改程序清单11.5,使之将一系列连续的随机漫步者位置写入到文件中。对于每个位置,用步号进行表示。另外,让该程序将初始条件(目标距离和步长)以及结果小结写入到该文件中。该文件的内容与下面类似:

Targer Distance: 100, Step Size: 20
0: (x,y) = (0, 0)
1: (x,y) = (-11.4715, 16.383)
2: (x,y) = (-8.68807, -3.42232)
...
26: (x,y) = (42.2919, -78.2594)
27: (x,y) = (58.6749, -89.7309)
After 27 Steps, the subject has the following location:
(x,y) = (58.6749, -89.7309)
or
(m,a) = (107.212, -56.8194)
Average outward distance per step = 3.97081


#include <iostream>
#
include <fstream>
using namespace std;
int main(int argc, char const *argv[])
{
    fstream f("./io1.txt", ios::out);
    int distance;
    int size;
    cin >> distance;
    cin >> size;
    f << "Targer Distance:" << distance << ",Step Size:" << size << "\n" ;
    double x = 0;
    double y = 0;
    f << 0 << ":(x, y)=(" << x << "," << y <<")\n";
    srand((int)time(NULL));
    for (int i = 0; i < size; ++i)
    {
        double tmpx = rand() / double(RAND_MAX);
        double tmpy = rand() / double(RAND_MAX);
        x += rand() / double(RAND_MAX) * 200 - 100;
        y += rand() / double(RAND_MAX) * 200 - 100;
        f << i << ":(x, y)=(" << x << "," << y <<")\n";
        cout << i << ":(x, y)=(" << tmpx << "," << tmpy <<")\n";
    }
    return 0;
}
发表于 2020-03-13 15:11:06 回复(0)