c++ rand()一直返回相同的数字
C++ rand() keeps returning the same number
我不明白为什么我的程序每轮都生成相同的随机数字。事实上,这个数字不会改变,除非我退出并重新启动程序。由于我是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();
...
相关文章:
- 函数如何使用引用返回所需的数字?
- 如何优化代码以返回最接近给定整数的数字,但给定列表中不存在?
- 返回 int 中可被 2 c++ 整除的所有数字的总和
- C++ python 中的函数返回数字而不是字符串
- 使用非托管导出将字符串从 C# 返回到C++将返回数字
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- 如何返回一串字母数字字符中的最大值(例如-1A003B3)?
- 将 MPFR 数字转换为字符串并返回
- C++ 递归:返回数字的最小偶数
- typeid.name 返回派生类类型之前的数字
- Fibbonaci 递归代码返回错误值,始终返回下一个数字
- 为什么我的阶乘数查找器返回以C++输入的数字?(已编辑)
- 尝试编写函数尝试从字符串中提取数字,但它返回不相关的数字
- 随机函数在循环中调用时返回相同的数字!C++
- 将字符转换为ASCII返回数字太大
- 为什么此范围基于语句返回一个数字太低的范围
- 根据另一个数字的可整除性返回子数组中的索引
- 如果数组中有重复的数字,如何返回'false'?
- 递归计算满足条件的值数并返回该数字
- C++余数以较高的数字返回 7