Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rand() returns the same number each time the program is run

Tags:

In this rather basic C++ code snippet involving random number generation:

include <iostream> using namespace std;  int main() {     cout << (rand() % 100);     return 0; } 

Why am I always getting an output of 41? I'm trying to get it to output some random number between 0 and 100. Maybe I'm not understanding something about how the rand function works?

like image 706
codedude Avatar asked Dec 15 '12 21:12

codedude


People also ask

Why does Rand keep giving me the same number?

The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.

Why does rand () give me the same number in C++?

Code. In the code below, the rand() function is used without seeding. Therefore, every time you press the run button, ​it generates the same number.

What does the function RAND () do?

Description. RAND returns an evenly distributed random real number greater than or equal to 0 and less than 1. A new random real number is returned every time the worksheet is calculated.

What is the return type of rand () function?

Explanation : return type of rand() is integer.


2 Answers

You need to change the seed.

int main() {      srand(time(NULL));     cout << (rand() % 101);     return 0; } 

the srand seeding thing is true also for a c language code.


See also: http://xkcd.com/221/

like image 55
0x90 Avatar answered Nov 07 '22 21:11

0x90


You need to "seed" the generator. Check out this short video, it will clear things up.

https://www.thenewboston.com/videos.php?cat=16&video=17503

like image 21
Aaron Avatar answered Nov 07 '22 20:11

Aaron