#How to have a new random number within a class's function?

16 messages · Page 1 of 1 (latest)

tepid haven
#

Im making a 2d Dots and Boxes games and Im trying to make a Random player, so I am trying to use srand() and use rand() everytime after to generate a number to pick a move on the board. My problem is that I keep getting the same random numbers, making it not random. I need help to progress further into my assignment because I need the randomness. If I can get any random number, then I can move on but I am completely stuck trying to generate a authentic random number. Do I need to have a member in my class for rand()? I just need to generate some random number everytime I call this function "PickMove"

Expected Output: Random Number everytime
Actual Output: Same number everytime I call the function

fair lanternBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

#

@tepid haven

Screenshots!

Your message appears to contain screenshots but no code. Please send code and error messages in text instead of screenshots if applicable!

agile iron
#

srand should be called exactly once at the beginning of your main. Never again afterwards.

tepid haven
#

okay so I cant have srand in a class function? always main?

agile iron
#

srand seeds the global random number generator. You shouldn't do this more than once while your program runs. Also, in general, do not use srand/rand. They have a lot of problems. Instead look at the more modern <random> library.

#

Where you do it once doesn't really matter, but in mainis the easiest place.

tepid haven
#

Okay, yes that has fixed my random numbers. Thank you very much for the quick response. Also, is <random> a vector? I cannot use vectors for this assignemnt but my next assignment will allow it.

agile iron
#

I don't have a beginner-friendly introduction to <random> at hand though...

fair lanternBOT
#

@tepid haven Has your question been resolved? If so, type !solved :)

tepid haven
#

okay Ill check that out, thank you again for helping and showing me new libraries.

#

!solved

fair lanternBOT
#

Cannot use outside a help channel

tepid haven
#

!solved

fair lanternBOT
#

Cannot use outside a help channel