随机数发生器不给我一个随机数

时间:2014-04-21 02:14:32

标签: c++

#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>

标题,以便它播种。

2 个答案:

答案 0 :(得分:4)

可能是因为你没有播种它。在第一次srand()来电之前尝试使用rand()

srand (time(NULL));

答案 1 :(得分:3)

您需要在使用之前为随机数生成器播种。在第一次使用rand()之前尝试插入此行:

srand (time(NULL));

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

This answer talks about why you need to seed the random number generator.