随机数生成器不会给我一个随机数

random number generator does not give me a random number

本文关键字:一个 随机数 随机数生成器      更新时间:2023-10-16
#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));

这将用当前时间为随机数生成器播种,从而允许更多的随机值。

这个答案说明了为什么需要为随机数生成器播种。