Generate Random Numbers Between 10 and 20 in C

This code demonstrates how to create a C function called 'random_number' to generate random integers between 10 and 20. It utilizes the rand() function for random number generation and srand() for seeding the random number generator.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int random_number() {
    int random = rand() % 11 + 10;  // generate a random number between 10 and 20
    return random;
}

int main() {
    srand(time(NULL));  // seed the random number generator with the current time

    int result = random_number();
    printf('%d
', result);

    return 0;
}

Explanation:

  1. random_number() Function:

    • rand() % 11 + 10: This expression is crucial for generating numbers within the desired range.
      • rand(): The rand() function produces a pseudo-random integer. This integer is typically within a large range (e.g., 0 to RAND_MAX, which is a system-defined constant).
      • % 11: The modulo operator (%) divides the random number by 11 and returns the remainder. This ensures the result is between 0 and 10.
      • + 10: Adding 10 shifts the range to 10 to 20.
  2. srand(time(NULL)):

    • time(NULL): This function obtains the current time in seconds since the Unix epoch. This value is used to seed the random number generator.
    • srand(): The srand() function initializes the random number generator. By seeding it with the current time, the generator will produce a different sequence of random numbers each time the program runs.

Important Considerations:

  • Seeding: It's essential to call srand(time(NULL)) only once at the beginning of your program. Multiple calls within a short time can lead to the same random number sequence.
  • Randomness: Keep in mind that these are pseudo-random numbers. They are generated using an algorithm, so they are not truly random.

This code provides a foundation for working with random numbers in C. You can adapt this function to generate random numbers within any desired range using the same principle of modulo and shifting.

C Programming: Generate Random Numbers Between 10 and 20

原文地址: https://www.cveoy.top/t/topic/bwiJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录