|
|
Random Number Generator: srand((unsigned)time(NULL)); rand()%10; 1. Open Borland C++ Builder. 2. Place a Button on the form. 3. Place a Label on the form. 4. Double click Button1. 5. Type the following red code in the Button1Click function: //This is what the Button1Click function should look like: void __fastcall TForm1::Button1Click(TObject *Sender) { static BOOL bSeeded = FALSE; if(!bSeeded) { srand((unsigned)time(NULL)); bSeeded = TRUE; } Label1->Caption = rand()%10; } //--------------------------------------------------------------------------- 6. Run the program, each time Button1 is pushed, a random number will be generated. The reserved word static will prevent the bSeeded variable from be redefined each time the button is pushed. Enclosing the srand statement withing the if statement prevents the ramdom number generator from being reseeded repeatedly. It only needs to be seeded once and the best way to to that is with the current time. The number 10 in the statement rand()%10; will produce a result of a random number 0 - 9. Adding a +1 (rand()%10+1) will produce a result of 1 - 10. |