#C++PrimerPlus# Chapter11_Exersice2_randwalk_v4
在Example13,Example14,Example15的例程中修改randwalk.cpp中的主函数,使的程序能对给定目标距离和步幅值重复多次计算,并统计随机的结果,给出最大值,最小值,平均值。
vector.h,vector.cpp可以不做修改,修改后的randwalk.cpp程序清单如下:
// randwork.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "vector.h"
int main()
{
using namespace std;
using VECTOR::Vector;
srand(time(0));
double direction;
Vector step;
Vector result(0.0, 0.0);
unsigned long steps = 0;
double target;
double dstep;
int times;
cout << "Enter target distance (q to quit): ";
while (cin >> target)
{
cout << "Enter step length: ";
if (!(cin >> dstep))
break;
cout << "Enter how mang times: ";
if (!(cin >> times))
break;
unsigned long* steps = new unsigned long [times];
for (int i = 0; i < times; i++)
{
steps[i] = 0;
while (result.magval() < target)
{
direction = rand() % 360;
step.reset(dstep, direction, Vector::POL);
result = result + step;
steps[i]++;
}
cout << "#" << i+1 << ": " << steps[i] << endl;
result.reset(0.0, 0.0);
}
unsigned long sMax, sMin, sSum;
sMax = steps[0];
for (int i = 1; i < times; i++)
sMax = sMax < steps[i] ? steps[i] : sMax;
sMin = steps[0];
for (int i = 1; i < times; i++)
sMin = sMin > steps[i] ? steps[i] : sMin;
sSum = steps[0];
for (int i = 1; i < times; i++)
sSum += steps[i];
cout << "Max: " << sMax << ", Min: " << sMin << endl;
cout << "Average: " << sSum / times << endl;
for (int i = 0; i < times; i++)
steps[0] = 0;
cout << "Enter target distance (q to quit): ";
}
cout << "Bye!\n";
cin.clear();
while (cin.get() != '\n')
continue;
return 0;
}
结束。