Question

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\srand_prg.cpp void value not ignored as it ought to be 

Using this code

#include <iostream>
#include <iomanip>
#include <sstream> 
#include <limits>
#include <stdio.h>

using namespace std ;

int main(){
    int rand_int;
    string close ;

    close == "y" ;

    cout << endl << endl ;
    cout << "\t ___________________________________" << endl ;
    cout << "\t|                                   |" << endl ;
    cout << "\t|   Pseudorandom Number Game!       |" << endl ;
    cout << "\t|___________________________________|" << endl ;
    cout << endl << endl ;

    while ( close != "y" ){

        rand_int = srand(9);
        cout << rand_int << endl ;

        cout << "  Do you wish to exit the program? [y/n]     " ;
        cin >> close ; }

}
Was it helpful?

Solution

srand doesn't return a random number, it just reseeds the random number generator. Call rand afterwards to actually get a number:

srand(9);
rand_int = rand();

OTHER TIPS

srand() generates a seed (which is the number used to initialize the random number generator) and must be called once per process. rand() is the function you are looking for.

If you don't know what seed to pick, use the current time:

srand(static_cast<unsigned int>(time(0))); // include <ctime> to use time()

call it this way.

srand(9);
rand_int = rand();

srand returns void function and doesn't return a value.

Here you can see more about it. You'll just have to call srand(9) and get the value of rand() after that, like J-16 SDiZ pointed out, who will be upvoted for this :)

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top