random number generator not working.

+1 Hannah kdlsfjsdalk · February 19, 2015

#include
#include
#include

using namespace std;

int main()
{
    //assign variables
    int random;
    char choice = ' ';
    char choiceAgain = ' ';
    char playAgain = ' ';

    //game introduction
    cout
I am trying to make a game, with the user selecting y/n and then a new option presents itself. But sometimes it just loops repeatedly.

currently, there's an infinite loop.

the infinite loop only runs for two seconds, giving a different looped answer each second. and then it gives me the "would you like to open another door?" prompt.

I think this is because it is determined by each whole second, so for each second a statement is true, it runs that infinitely until the next second comes by. maybe there's another way to do it rather than seconds?

Post a Reply

Replies

Oldest  Newest  Rating
+1 Jay Deshaun · February 19, 2015
Can you post your whole code please?

Check this out if anything:
http://www.cplusplus.com/reference/cstdlib/rand/
+1 Dol Lod · February 19, 2015
srand is the only function that will make rand actually produce random results and should be called with some integer value, preferably 0, before rand is called. After that initial call, the input will be different every time. I can't see code to comment on anything else. 
+1 Çağlan Turgut · February 19, 2015
@Arjun, Yes it is called a random seed. Random numbers are not actually random, they are complex algorithms that takes a number (your seed) and generates some numbers from it. If it is not included, most of the compilers will give errors. 
0 Dol Lod · February 20, 2015
Really. Sorry, I guess I didn't learn about srand correctly. 
0 Cardinal Coog · February 21, 2015
Try something like this:


Set the random seed w/
srand(time(NULL)); or srand(time(0));

and then use

randomNumber =  rand() % 50 + 1;

change the 50 to whatever you want.
0 Cardinal Coog · February 21, 2015
@krootushas: That it false. Using srand with time changes the random algorithm every second. Therefore, it's a close to random as you can get.
0 Cardinal Coog · February 21, 2015
@Linguist Llama, while what you stated is correct, you're relying on third party software.
Do you know of a way to write C++ code that is independent of Fortuna or Yarrow and more random than what I suggested?
If you do, please post that code so I can learn to write that way :)
0 c student · February 21, 2015
basically, in general...  true randomness requires entropy which occurs from sources such as physical phenomena, not from a single dynamic variable inserted into a calculation, from what i've read about rngs lately.
  • 1

C++

107,044 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator