Hi im writing a program to simulate a slot machine, where a user enteres a coin and has a 70% chance of winning (say 3 coins). Anyways, I have a class slotMachine with a public int random() function.

Here is the function:

int slotMachine::random()
    srand( time(NULL));

    randomNum = rand() % 7 + 1;  // from 1 to 7
    return randomNum; 

The function should generate a number between 1 and 7, if the user enters a number between this they win.
However, when I run the program and test to see what number the function prints it always prints 5. Is this because srand(time(NULL)) generates a long value, and when I try to convert it to an integer it only prints the first number of the geterated long type value? How can I fix this?

Alright I think I got it.

int slotMachine::random()
    //srand ( time(NULL) );

    randomNum = rand() & 10 + 1;  // from 1 to 10
    return randomNum; 

Random number between 1 and 10 means 70% chance of winning.

the srand() must be putted into your main() function, so it can seed correctly..
there is no need to change nothing else.. just put it on main() and test it!

Try to get out the srand() part from that function. Srand() generates a seed for your rand() function, thus it should be put just 1 time in your program, most likely in your main function since it's the starting point of your program and it is called just 1 time. If you put it in your slot function, whenever you call that function the srand() will be called too, with the same parameter, thus generating the same random number.

Ahh of course. Got it. Thanks

Also, the new C++ Standart has another, and ( for my point of view ) better random number generator.
Check it out: Click Here
PS: It depends of availability, so, last time I checked, works on VS2012, but on GCC still a pseudo-random number generator!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.