随机数生成器不会给我一个随机数
random number generator does not give me a random number
#include <cstdlib>
#include <cmath>
#include <string>
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
int main()
{
int size = 0;
int test = 0;
string phrase, sentence;
test = rand() % 4 + 1;
cout << "#" << test << endl;
switch(test)
{
case 1:
phrase = "thing";
sentence = "computer science";
case 2:
phrase = "Subject";
sentence = "math and science";
case 3:
phrase = "Subject";
sentence = "pony and unicorn";
case 4:
phrase = "Subject";
sentence = "dinosaurs and rhino";
};
cout << "The phrase is..." << phrase << endl;
cout << "Here is your sentence..." << sentence << endl;
int length;
length = sentence.length();
char letter;
int arysize[length];
for(int z = 0; z < length; z++)
{
arysize[z] = 0;
}
int count = 0;
while(count != 10)
{
cout << "Enter a letter" << endl;
cin >> letter;
for(int j = 0;j < length; j++)
{
if(sentence[j] == letter)
{
arysize[j] = 1;
}
else if (sentence[j] == ' ')
arysize[j] = 1;
}
for (int m = 0; m < length; m++)
{
if(arysize[m] == 1)
{
cout << sentence[m];
}
else
cout << "_";
}
count++;
cout << "You have " << 10 - count << " tries left." << endl;
}
}
很抱歉造成了这样的混乱,因为我正在创建一个样本,并正在进行试错以获得结果。当我在4+1中使用rand((时,我应该得到一个介于1-4之间的数字。但每当我运行这个程序时,我总是得到4。为什么它不是随机选择一个数字,而是总是给我相同的数字?
伙计们!只是为了确保如果其他人正在阅读。。。你必须包括
#include <ctime>
收割台以便播种。
可能是因为您没有对其进行种子设定。请在第一次调用rand()
之前尝试使用srand()
,如下所示:
srand (time(NULL));
在使用随机数生成器之前,您需要对其进行种子设定。请尝试在第一次使用rand()
之前插入此行:
srand (time(NULL));
这将用当前时间为随机数生成器播种,从而允许更多的随机值。
这个答案说明了为什么需要为随机数生成器播种。
相关文章:
- 如何在 c++ 中从数组中选择一个随机数?
- 从大范围内生成一个随机数,但从大范围的中间开始生成较小的范围
- 如何在C++中创建数字列表,以便它可以选择一个随机数?
- 在[0,1)C 之间生成一个随机数
- 在此过程中的纸牌游戏程序.不知道为什么我会得到一个随机数-858993460
- 为什么递增指针会给出一个随机数,而不是内存地址
- 如何使用Linux GetRandom系统调用来在范围内生成一个随机数
- visual如何在C++中创建一个随机数数组
- 选择一个随机方块并生成一个随机数
- 在一个间隔内生成一个随机数,但某些数字除外:EXC_BAD_ACCESS
- 当你复制一个随机数引擎和随机数分布时会发生什么?
- 给一个数组一个随机数
- 从整数列表中选择一个随机数
- 提供的示例代码返回一个随机数,即使在抛出异常之后也是如此(提供的代码)
- 如何使用openssl获得一个随机数
- 为什么在头文件的第一行放一个随机数
- C++和Qt:不要在x分钟内选择一个随机数
- 随机数生成器不会给我一个随机数
- 有没有一种方法可以让我从0-10亿中得到一个随机数
- 构造函数中变量的启动不起作用,而是给我一个随机数