这是为了模拟投掷 2 个 6 面骰子而编写的。但是当我投入 10 次投掷时,它会随机投掷任意数量的 (4, 5, 6 etc.) 。我错过了什么吗?
#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");
}