【问题标题】:Generate two different random numbers生成两个不同的随机数
【发布时间】:2017-04-16 21:51:46
【问题描述】:

我将使用 C++ 创建一个简单的“掷骰子”游戏

在“Craps”中,当玩家掷骰子不是立即输赢的点时,他们需要再次掷骰子

但是当需要再次掷骰子时,我无法更改骰子数量

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

void again(int first) {
    srand(time(NULL));
    int dice11, dice22, total2;
    do {
        dice11 = (rand() % 6 + 1);
        dice22 = (rand() % 6 + 1);
        total2 = dice11 + dice22;
        cout << "Player throw " << total2 << endl;
        if (total2 == first)
            cout << "Player Win" << endl;
        if (total2 == 7)
            cout << "Player Lose" << endl;
    } while (total2 != first);

}



int main() {
    srand(time(NULL));
    int dice1, dice2,total;
        dice1 = (rand() % 6 + 1);
        dice2 = (rand() % 6 + 1);
        total = dice1 + dice2;

        if (total == 7 || total == 11)
            cout << "Player throw " << total << " Player Win" << endl;
        else
            if (total == 2 || total == 8 || total == 12)
                cout << "Player throw " << total << " Player Lose" << endl;
            else
            {   
                cout << "Player throw " << total << endl;
                again(total);
            }


    system("pause");
    return 0;
}

在程序中,我已经创建了一个再次使用“srand()”的函数,但它仍然不起作用

【问题讨论】:

  • 您应该在您的程序中只调用一次srand() - 在main() 中的调用应该会这样做。在again() 中调用它只会让事情变得更糟。如果您仍有问题,请编辑您的问题以提供minimal reproducible example - 包括准确解释发生的情况与您的预期。

标签: c++


【解决方案1】:

在程序中,我已经创建了一个再次使用“srand()”的函数,但它仍然不起作用

那是因为你又使用了srand()

只需在程序开始时执行一次。

这在the cppreference documentation 中有解释。您是否在没有文档的情况下进行编程?

【讨论】:

    【解决方案2】:

    您对srand 的第二次调用(在函数again 中)很可能将随机数生成器初始化为与前一次调用相同的种子。 time() 计算秒数(主要见 C++ reference)。不要重新初始化随机数生成器 - 除非您想重新创建之前生成的随机数序列。

    【讨论】:

      猜你喜欢
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多