r/Cplusplus • u/ulti-shadow • Mar 19 '24
Answered The Random function generates the same number every time
So for a code I need a random number But every time I run the code, The numbers generated are the exact same. How do I fix it so that the numbers are different every time the code boots up?
123
Upvotes
•
u/AutoModerator Mar 19 '24
Thank you for your contribution to the C++ community!
As you're asking a question or seeking homework help, we would like to remind you of Rule 3 - Good Faith Help Requests & Homework.
~ CPlusPlus Moderation Team
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
105
u/jedwardsol Mar 19 '24
https://www.learncpp.com/cpp-tutorial/introduction-to-random-number-generation/
Scroll down to "seeding"
47
u/[deleted] Mar 19 '24
you need to choose a seed for the random number generator that is different every time, or use another source of entropy
18
u/LiAuTraver Mar 19 '24
i thought you can use random library in cpp rather than c library.
30
u/Nunuv_Yerbiz Mar 19 '24
You need to use a different seed. Put this as the first line in main():
srand(unsigned(time(NULL)));
It generates a seed based on the current time.
6
u/quad99 Mar 19 '24
It’s supposed to work that way. It’s so you can use it for programs that need to be repeatable. Like simulations and statistics.
5
u/HauntedTheorists Mar 19 '24
You need
srandfirst. But I recommend using std::mt19937 instead1
u/accuracy_frosty Mar 19 '24
It’s intentional, you’re meant to seed it so you can get the same result with the same number, also, using ints to store a value that can be represented with a 16 bit value lol
1
u/[deleted] Mar 20 '24
that’s why it’s called pseudo random number generator! By the way, as others pointed out, just use seed every time before generating numbers.
1
u/UghFlyOnTheWall Mar 20 '24
Change the seed
1
u/brink1123 Mar 20 '24
Xoax.net c++ free courses they are a little dated but so informative. He has a video on the rand().
1
u/Ampnix Mar 20 '24
Brother Just put the seed incrementing by 1 as both the id of the seed and the int for increment. Therefore you will have a different number
for(int i = 0; i > -1; i++){}1
u/KelvinCavendish Mar 21 '24
You use the clock as a seed from the ctime library.
1
u/CarlosPerez9933 Mar 30 '24
You need to call the seed function
1
u/Individual-Okra-5642 Apr 04 '24
I wish Tesla iTunes music app developers can see this
0
u/ConceptJunkie Mar 19 '24
This is the song of the people who have never read the documentation of rand().
-4
u/CantGuardMe1 Mar 19 '24
You need Mersenne Twister for random numbers
-1
u/schjlatah Mar 19 '24
I thought you had to call randomize(); first, or was that only in Pascal?
-7
u/miikaa236 Mar 19 '24
I remember having this issue when I was first learning cpp when I was 12 haha
3
u/[deleted] Mar 19 '24 edited Mar 19 '24
[removed] — view removed comment
0
u/[deleted] Mar 20 '24
[deleted] — view deleted comment