为什么 rand() 总是返回相同的值? [英] Why does rand() always return the same value?
本文介绍了为什么 rand() 总是返回相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
在 C 中生成随机数
使用rand生成随机数
我正在尝试生成随机数,但我不断得到数字 41.在这样一个简单的片段中可能会出现什么问题?
I'm trying to generate random numbers but i'm constantly getting the number 41. What might be going so wrong in such a simple snippet?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a = rand();
printf("%d",a);
return 0;
}
感谢您的帮助.
推荐答案
你需要给不同的种子,例如:
You need to give a different seed, for example:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int a;
srand ( time(NULL) );
a = rand();
printf("%d",a);
return 0;
}
这篇关于为什么 rand() 总是返回相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文