Problems with srand(), C++

前端 未结 5 804
被撕碎了的回忆
被撕碎了的回忆 2021-01-28 23:30

I\'m trying to write a program that generates a pseudorandom numbers using a seed. However, I\'m running into problems.

I get this error

39 C:\\Dev-Cpp\         


        
5条回答
  •  無奈伤痛
    2021-01-28 23:45

    You're using srand incorrectly, that particular function is for setting the seed for later calls to rand.

    The basic idea is to call srand once with an indeterminate seed, then call rand continuously to get a sequence of numbers. Something like:

    srand (time (0));
    for (int i = 0; i < 10; i++)
        cout << (rand() % 10);
    

    which should give you some random numbers between 0 and 9 inclusive.

    You generally don't set the seed to a specific value unless you're testing or you want an identical sequence of numbers for some other reason. You also don't set the seed each time before you call rand since you're likely to get the same number repeatedly.

    So your particular while loop would be more like:

    srand (9); // or use time(0) for different sequence each time.
    while (close != "y") {  // for 1 thru 9 inclusive.
        rand_int = rand() % 9 + 1;
        cout << rand_int << endl;
    
        cout << "Do you wish to exit the program? [y/n]? ";
        cin >> close;
    }
    

提交回复
热议问题