为什么rand()总是返回相同的值?

Umu*_*mut 5 c random

可能重复:使用rand
在C
中生成随机数以生成随机数

我正在尝试生成随机数,但我不断得到数字41.这样一个简单的片段可能会出错?

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

int main(void)
{
    int a = rand();
    printf("%d",a);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

感谢帮助.

MBy*_*ByD 15

您需要提供不同的种子,例如:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
    int a;
    srand ( time(NULL) );
    a = rand();
    printf("%d",a);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)