骰子计数器不能正常工作(初学者)

Seb*_*Seb 1 c++ counter

这是为了模拟被抛出的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");
}
Run Code Online (Sandbox Code Playgroud)

us2*_*012 6

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

  • 您的throwDice函数并没有模拟两个六面骰子被投掷,但它模拟一个11面的骰子(印有号码2-11)被抛出.这有所不同.(这不是一个编程问题,而是一个数学问题.一旦你理解了它背后的数学,就很容易纠正你的功能.)