+ 4
Can someone explain to me how the rand() work ? Language C++ . I don’t get it ! What do we use it for ?
4 Respuestas
+ 5
if you use only rand() it will help you generate pseudo-random numbers (not really generated randomly but following a specific way so you may keep getting the same number over and over again )
----> use :
• rand() % 100; // returns a number between 0 and 100
• rand()%100 +1 //here +1 is used to skip 0 and generate a number between 1 and 100 so if you replace 1 by 50 it will generate a number between 50 and 100
note : to generate truly random numbers you need more lines of code. this website may be useful for you : cplusplus.com
+ 4
thank you so much !
+ 2
thank you Robin
0
rand() can be used to generate random numbers.
/* rand example: guess the number */
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
int iSecret, iGuess;
/* initialize random seed: */
srand (time(NULL));
/* generate secret number between 1 and 10: */
iSecret = rand() % 10 + 1;
do {
printf ("Guess the number (1 to 10): ");
scanf ("%d",&iGuess);
if (iSecret<iGuess) puts ("The secret number is lower");
else if (iSecret>iGuess) puts ("The secret number is higher");
} while (iSecret!=iGuess);
puts ("Congratulations!");
return 0;
}