在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;
}
结束。
原文链接: https://www.cnblogs.com/zhuangdong/archive/2013/05/04/3059834.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/87075
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!