Random no. function dispays the same number

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Apr 2009
Posts: 147
Reputation: gretty is an unknown quantity at this point 
Solved Threads: 7
gretty gretty is offline Offline
Junior Poster

Random no. function dispays the same number

 
0
  #1
Aug 2nd, 2009
hi

My random number function is meant to loop 6 times & output 6 different numbers. But instead it outputs 6 of the same numbers. How do I fix it?

Any advice would be really helpful.

  1. #include <iostream>
  2. #include <fstream>
  3. #include <cstdlib>
  4. #include <ctime>
  5. #include <iomanip>
  6. #include <string>
  7.  
  8.  
  9. using namespace std;
  10.  
  11. int random(int max)
  12. {
  13. srand(time(NULL));
  14.  
  15. return ((rand()%max)+1);
  16. }
  17.  
  18. int main()
  19. {
  20.  
  21. for (int i=0; i<6; i++) {
  22. used_nos[i] = random(40);
  23. cout << used_nos[i] << endl;
  24. }
  25.  
  26. return 0;
  27. }
Last edited by gretty; Aug 2nd, 2009 at 5:05 am.
Reply With Quote Quick reply to this message  
Join Date: May 2007
Posts: 1,868
Reputation: twomers has a spectacular aura about twomers has a spectacular aura about twomers has a spectacular aura about 
Solved Threads: 56
twomers's Avatar
twomers twomers is offline Offline
Posting Virtuoso

Re: Random no. function dispays the same number

 
1
  #2
Aug 2nd, 2009
I'd imagine if you were to wait in the for loop for about a second per iteration it'd be different.

The problem is that you're reseeding the rand function so quickly it's being reseeded off the same value. You only need to seed it once, so do it at the start of main.
  1. #include <iostream>
  2. #include <fstream>
  3. #include <cstdlib>
  4. #include <ctime>
  5. #include <iomanip>
  6. #include <string>
  7.  
  8.  
  9. using namespace std;
  10.  
  11. int random(int max)
  12. {
  13.  
  14. return ((rand()%max)+1);
  15. }
  16.  
  17. int main()
  18. {
  19.  
  20. srand(time(NULL));
  21. for (int i=0; i<6; i++) {
  22. used_nos[i] = random(40);
  23. cout << used_nos[i] << endl;
  24. }
  25.  
  26. return 0;
  27. }

For further clarification... srand takes time(null) in your code, which updates every second, I believe. So if srand was in the function and if the loop executed for over a second you'd get different numbers out every different second.
Last edited by twomers; Aug 2nd, 2009 at 5:32 am.
I blag!?
"Mr Kitty, you have to live in the attic now. Here, write a diary."
I am the Walrus!
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC