gpt4 book ai didi

c++ - 骰子计数器无法正常工作(初学者)

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:27:19 25 4
gpt4 key购买 nike

这是为了模拟 throw 2 个 6 面骰子而编写的。但是当我 throw 10 次时,它会随机 throw 任意数量的 throw (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");
}

最佳答案

  • 您调用一次 throwDice() 以生成抛出(正确),然后在您的 if 语句中的每个评估条件中再次调用(不正确)。将抛出的结果保存在一个变量中,并在您的检查中使用该变量。

  • 您的 throwDice 函数模拟掷出两个 6 面骰子,但它模拟一个 11 面骰子(上面印有数字 2-11)它)被抛出。这很重要。 (虽然这不是编程问题,而是数学问题。一旦理解了它背后的数学原理,就很容易更正您的函数。)

关于c++ - 骰子计数器无法正常工作(初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14908539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com