testdice.cpp
来自「C++&datastructure书籍源码,以前外教提供现在与大家共享」· C++ 代码 · 共 47 行
CPP
47 行
#include <iostream>
using namespace std;
#include "prompt.h"
#include "dice.h"
// simulate rolling two dice to obtain all possible sums
// repeat the "experiment" specified number of times
// Owen Astrachan, 8/9/94, modified 6/9/95, 4/20/99
double RollTest(int target,int experiments);
int main()
{
int numTimes; // for one trial
long totalRolls; // accumulate for all trials
int k;
numTimes = PromptRange("number of 'trials' ",100,20000);
totalRolls = 0;
for(k=2; k <= 12; k++)
{ cout << k << "\t" << RollTest(k,numTimes) << endl;
}
return 0;
}
double RollTest(int target, int trials)
// precondition: 2 <= target <= 12, 0 < trials
// postcondition: returns average # of rolls needed to obtain target
// trying 'trials' times
{
Dice d1(6);
Dice d2(6);
int total = 0;
int k;
for(k=0; k < trials; k++)
{ int numRolls = 1; //first time through loop is 1 roll
while (d1.Roll() + d2.Roll() != target)
{ numRolls += 1;
}
total += numRolls;
}
return double(total)/trials;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?