943,923 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 460
  • C++ RSS
Aug 2nd, 2009
0

Random no. function dispays the same number

Expand Post »
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.

C++ Syntax (Toggle Plain Text)
  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.
Similar Threads
Reputation Points: 10
Solved Threads: 7
Junior Poster
gretty is offline Offline
158 posts
since Apr 2009
Aug 2nd, 2009
1

Re: Random no. function dispays the same number

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.
C++ Syntax (Toggle Plain Text)
  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.
Reputation Points: 453
Solved Threads: 57
Posting Virtuoso
twomers is offline Offline
1,873 posts
since May 2007

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Exceptions handling problems
Next Thread in C++ Forum Timeline: Mp3 bitstream





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC