#C++PrimerPlus# Chapter11_Exersice2_randwalk_v4

本文介绍了一个基于C++的随机行走模拟程序。通过对randwalk.cpp的修改,该程序能够针对指定的目标距离和步长进行多次模拟实验,并统计每次实验所需的步数,最终输出这些步数的最大值、最小值及平均值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值