+ 3

Why does my function rand() return the same number all the time?

#include <iostream> #include <cstdlib> using namespace std; int main() { cout << rand(); }

19th Sep 2017, 10:49 PM
Oleksandr Rubtsov
Oleksandr Rubtsov - avatar
7 ответов
+ 11
.... the seed is the same every time.. of course the results of rand will be the same. What happens if you provide a unique seed each time you execute the program. Say with providing the current time as a seed. Here is some information which may help with your understanding. Hope it helps http://www.cplusplus.com/reference/cstdlib/srand/
19th Sep 2017, 11:19 PM
jay
jay - avatar
+ 11
You are welcome Alexander. I will also be re-examining this section of the course as you are definitely not the first person to ask this after completing this section. I would like to see if I could suggest any improvements to the explanation they provide. If you have any further doubts or confusion please do not hesitate to ask
19th Sep 2017, 11:30 PM
jay
jay - avatar
+ 7
re-examine the course *functions | rand () function* You will see that srand() is required to be used in conjunction with rand().
19th Sep 2017, 11:04 PM
jay
jay - avatar
+ 4
Thank you so much for attention jay! I'll sort this out
19th Sep 2017, 11:23 PM
Oleksandr Rubtsov
Oleksandr Rubtsov - avatar
+ 4
#include <cstdlib> #include <ctime> #include <iostream> int main() { srand(time(nullptr)); for (int i = 0; i< 10; ++i) { cout << rand() % 10 + 1 << endl; } return 0; }
20th Sep 2017, 12:51 AM
Zeke Williams
Zeke Williams - avatar
+ 1
thanks for answer jay, but i got a similar situation with srand() function.. Explain please why in this code i got similar numbers again? int main () { srand(98); for (int x = 1; x <= 10; x++) { cout << 1 + (rand() % 6) << endl; } }
19th Sep 2017, 11:09 PM
Oleksandr Rubtsov
Oleksandr Rubtsov - avatar
- 1
I have only 41 in all attempts to run this code.. :-/
19th Sep 2017, 10:50 PM
Oleksandr Rubtsov
Oleksandr Rubtsov - avatar