How to generate random floating point numbers in C language?

In C language, you can use the rand() function from the standard library to generate random integers, and then convert them to random floating point numbers.

Here is a sample code:

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

int main() {
    // 设置种子,以确保每次运行产生不同的随机数
    srand(time(NULL));

    // 产生0到RAND_MAX之间的随机整数
    int randomInt = rand();

    // 将随机整数转换为0到1之间的随机浮点数
    double randomFloat = (double)randomInt / RAND_MAX;

    printf("随机浮点数: %.4f\n", randomFloat);

    return 0;
}

In the above code, the srand function is used with time(NULL) as the seed to initialize the random number generator, so that a different random sequence is generated each time the program is run. Then the rand function is used to generate a random integer between 0 and RAND_MAX, which is then divided by RAND_MAX to get a random floating point number between 0 and 1. Finally, the printf function is used to output the value of the random floating point number.

Please note that the above code only generates a random floating-point number between 0 and 1. If you want to generate random floating-point numbers in other ranges, you can use multiplication and addition to make the appropriate transformations.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds