c++ rand()一直返回相同的数字

C++ rand() keeps returning the same number

本文关键字:数字 返回 一直 rand c++      更新时间:2023-10-16

我不明白为什么我的程序每轮都生成相同的随机数字。事实上,这个数字不会改变,除非我退出并重新启动程序。由于我是c++新手,所以这应该是一个我不知道的相当微不足道的错误。以下是我的代码,提前感谢您的帮助。

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
int getRandNum();
int main()
{
    int randNum = getRandNum();
    srand((unsigned int) time(NULL));
.
.
.
}
int getRandNum()
{
    int randNum;
    randNum = rand() % 3 + 1;
    return randNum;
}

您只调用一次computerChoice函数,并将此结果用于所有后续操作。

此外,调用必须在用srand播种随机生成器之后完成,就像@ZdeslavVojkovic正确提到的

从函数getComputerChoice()调用rand。但是,该函数是在使用srand设置种子之前调用的。

您需要在rand函数第一次调用之前调用srand,这也意味着在getComputerChoice之前

您需要将int computerChoice = getComputerChoice();移动到do循环中。上面的代码在开始时选择一个选项,然后不再选择另一个。

你只要在getPlayerChoice()下面写getComputerChoice(),你的问题就解决了。

playerChoice = getPlayerChoice();
computerChoice = getComputerChoice();

算法中的问题,您只在main()的开头调用getComputerChoice()一次,但您需要在do中这样做…:

...
if(playQuitOption == 'p' || playQuitOption == 'P')
    {
        cout << endl;
        playerChoice = getPlayerChoice();
        computerChoice = getComputerChoice();
...