i want to write a random number generator that generates a number between 1 to 100. i have tried random() function but it prints out the same number every time. HELP pls ...
There are two ways of doing this. The easy C-style way is to use the rand() function - for that you will need to seed the random number generator as well:
1 2 3 4 5 6 7 8 9
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(0)); // seed the random number generator
printf("%d\n", rand() % 100 + 1); // print a number between 1 and 100
return EXIT_SUCCESS;
}
Alternately, you could do the C++ style way for 'more random' numbers, using the various objects in the <random> header:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <random>
#include <ctime>
int main() {
std::mt19937 gen (std::time(nullptr)); // a random number generator
std::uniform_int_distribution<int> dist (1, 100); // the distribution
std::cout << dist(gen) << std::endl;
return 0;
}
Also, note that random() is a Borland extension, not a standard C or C++ function.