rand() question

This is a discussion on rand() question within the C++ Programming forums, part of the General Programming Boards category; why am i getting the same numbers every time i run this code ? Code: #include <iostream> using namespace std; ...

  1. #1
    Registered User Spectrum48k's Avatar
    Join Date
    May 2002
    Posts
    66

    rand() question

    why am i getting the same numbers every time i run this
    code ?

    Code:
    #include <iostream>
    using namespace std;
    
    
    int main()
    {
    	int number, i, j;
    
    	for(j=1; j<30; j++){
    		for(i=1; i<10; i++){
    			number = rand()%100;
    			cout << number << ' ';
    			}
    		cout << '\n';
    	}
    	
    return 0;
    }

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    look up srand() in your helpfiles.

    Read the FAQ!!!
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    The Pantless Man CheesyMoo's Avatar
    Join Date
    Jan 2003
    Posts
    262
    Seed it.

  4. #4
    Registered User Spectrum48k's Avatar
    Join Date
    May 2002
    Posts
    66

    answer

    thnx.

    Code:
    #include <stdlib.h>
    #include <time.h>
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	srand((unsigned)time(NULL)); //Casts time's return to unsigned
    	int number, i, j;
    
    	for(j=1; j<30; j++){
    		for(i=1; i<10; i++){
    			number = rand()%100;
    			cout << number << ' ';
    			}
    		cout << '\n';
    	}
    	
    return 0;
    }
    Last edited by Spectrum48k; 04-03-2003 at 06:14 PM.
    its alive... its ALIVE... ITS...AL...IIIVE !!!!!!!!!

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21