这是为了模拟被抛出的2个6面骰子。但是当我投入10次投掷时,它会随机投掷任意数量(4,5,6等)。我错过了什么吗?
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int throwDice() // returns random number ranged 2-12
{
int x = (rand() % 11) + 2;
return x;
}
int main()
{
srand (time(NULL));
int y;
cout << "Roll dice how many times?" << endl;
cin >> y;
int a2 = 0;
int a3 = 0;
int a4 = 0;
int a5 = 0;
int a6 = 0;
int a7 = 0;
int a8 = 0;
int a9 = 0;
int a10 = 0;
int a11 = 0;
int a12 = 0;
for (int i = 0; i < y; i++)
{
throwDice();
if (throwDice() == 2)
a2++;
else if (throwDice() == 3)
a3++;
else if (throwDice() == 4)
a4++;
else if (throwDice() == 5)
a5++;
else if (throwDice() == 6)
a6++;
else if (throwDice() == 7)
a7++;
else if (throwDice() == 8)
a8++;
else if (throwDice() == 9)
a9++;
else if (throwDice() == 10)
a10++;
else if (throwDice() == 11)
a11++;
else if (throwDice() == 12)
a12++;
}
cout << "2 = " << a2 << endl;
cout << "3 = " << a3 << endl;
cout << "4 = " << a4 << endl;
cout << "5 = " << a5 << endl;
cout << "6 = " << a6 << endl;
cout << "7 = " << a7 << endl;
cout << "8 = " << a8 << endl;
cout << "9 = " << a9 << endl;
cout << "10 = " << a10 << endl;
cout << "11 = " << a11 << endl;
cout << "12 = " << a12 << endl;
system("pause");
}
答案 0 :(得分:6)
您正在调用throwDice()
一次以生成抛出(正确),然后再次调用if
语句中的每个评估条件(不正确)。将throw的结果保存在变量中,并在检查中使用该变量。
你的throwDice
函数不模拟两个6面骰子被抛出,但它模拟一个11面骰子(上面印有数字2-11)是抛出。这有所不同。 (这不是一个编程问题,而是一个数学问题。一旦你理解了它背后的数学,就很容易纠正你的功能。)
答案 1 :(得分:2)
我会写这段代码:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int throwDice() // returns random number ranged 2-12
{
int x = (rand() % 11) + 2;
return x;
}
int main()
{
srand (time(NULL));
int y;
cout << "Roll dice how many times?" << endl;
cin >> y;
int total[13];
for( int i = 2; i <= 12; i++ )
total[i] = 0;
for (int i = 0; i < y; i++)
{
total[throwDice()]++;
}
for (int i = 2; i <= 12; i++)
cout << i << " = " << total[i] << endl;
system("pause");
}
更简单,更容易理解。
嗯,以下是您的代码存在的问题:
您正在所有throwDice
语句中重复调用if
函数。您只需要在循环的每次迭代中调用一次,存储结果并比较结果。你不应该每次都打电话给比赛。每次通话都会给你一个新的结果。
您还可以在我的代码中看到使用数组如何简化整个代码。在这里,我浪费了两个数组元素(0和1),这可以通过索引的简单算法来避免。
答案 2 :(得分:1)
你的循环应该看起来像
int result;
for (int i = 0; i < y; i++)
{
result = throwDice();
if (result == 2)
a2++;
else if (result == 3)
a3++;
else if (result == 4)
a4++;
else if (result == 5)
a5++;
else if (result == 6)
a6++;
else if (result == 7)
a7++;
else if (result == 8)
a8++;
else if (result == 9)
a9++;
else if (result == 10)
a10++;
else if (result == 11)
a11++;
else if (result == 12)
a12++;
}
此外,throwDice()
功能不等于投掷2个骰子。你已经创建了一个能够将所有值从2滚动到12的平等机会。当你滚动2个骰子时,它比6更容易滚动6个。你应该在两个之间创建两个数字。 1和6并添加它们以获取throwDice()
函数的返回值。
答案 3 :(得分:0)
我知道这不能回答这个问题,但我不禁想知道如果你可以使用C ++ 11,你是否会受益:
#include <random>
std::minstd_rand prng;
std::uniform_int_distribution<int> dice (1, 6);
int throwDice ()
{
return (dice(prng) + dice(prng));
}
int main ()
{
prng.seed(time(NULL));
// (code)
}