In C, how to pick a random number between 0 and 100 included?
In C, the rand()
function allows to generate a pseudo-random number. The following code allows to restrict the draw between 0 and 100 inclusive.
x = rand()%101;
The generic formula is detailed here. Bellow is the complete code that initializes the pseudorandom generator to avoid always drawing the same numbers:
#include <stdio.h> // For printf
#include <stdlib.h> // For rand() srand()
#include <time.h> // For time()
int main(void) {
// Initialize the pseudo random generator
// Without this line, we would always pick the same number
srand(time(NULL));
// Generate a random number between 0 and 100 (included)
int x = rand()%101;
// Display the number
printf("Random number : %d\n", x );
return 0;
}
In C, the rand()
function allows to generate a pseudo-random number. The following code allows to restrict the draw between 0 and 100 inclusive.
x = rand()%101;
The generic formula is detailed here. Bellow is the complete code that initializes the pseudorandom generator to avoid always drawing the same numbers:
#include <stdio.h> // For printf
#include <stdlib.h> // For rand() srand()
#include <time.h> // For time()
int main(void) {
// Initialize the pseudo random generator
// Without this line, we would always pick the same number
srand(time(NULL));
// Generate a random number between 0 and 100 (included)
int x = rand()%101;
// Display the number
printf("Random number : %d\n", x );
return 0;
}
In C, the rand()
function allows to generate a pseudo-random number. The following code allows to restrict the draw between 0 and 100 inclusive.
x = rand()%101;
The generic formula is detailed here. Bellow is the complete code that initializes the pseudorandom generator to avoid always drawing the same numbers:
#include <stdio.h> // For printf
#include <stdlib.h> // For rand() srand()
#include <time.h> // For time()
int main(void) {
// Initialize the pseudo random generator
// Without this line, we would always pick the same number
srand(time(NULL));
// Generate a random number between 0 and 100 (included)
int x = rand()%101;
// Display the number
printf("Random number : %d\n", x );
return 0;
}
# | ID | Query | URL | Count |
---|