+ 3
Why does my function rand() return the same number all the time?
#include <iostream> #include <cstdlib> using namespace std; int main() { cout << rand(); }
7 Respostas
+ 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/
+ 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
+ 7
re-examine the course *functions | rand () function*
You will see that srand() is required to be used in conjunction with rand().
+ 4
Thank you so much for attention jay!
I'll sort this out
+ 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;
}
+ 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;
}
}
- 1
I have only 41 in all attempts to run this code.. :-/