getrandomint() in C
- User
get_random_int() in C
- Assistant
Here is an example of a function
get_random_int()in C that generates a random integer within a given range:#include <stdio.h> #include <stdlib.h> #include <time.h> int get_random_int(int min, int max) { // Seed the random number generator with the current time srand(time(NULL)); // Generate a random number within the specified range int num = (rand() % (max - min + 1)) + min; return num; } int main() { int minValue = 1; int maxValue = 100; int randomInt = get_random_int(minValue, maxValue); printf("Random Integer: %d\n", randomInt); return 0; }In this example, the
get_random_int()function takes two parametersminandmax, which represent the minimum and maximum values of the range from which we want to generate a random integer. The function usessrand()to seed the random number generator with the current time, so that it produces different random sequences every time the program is run. Then, it uses to generate a random number within the specified range by using the modulo operator and adding the value. Finally, the function returns the generated random number.