rand()问题在C编程? [英] rand() issue in C programming?
问题描述
所以是的,这可能看起来有点noobish,但因为我教自己C在Java后变得合理,我已经运行进入一些麻烦。我试图在C中使用rand()函数,但我只能调用一次,当它做,它总是生成相同的随机数,这是41.我使用的是Microsoft Visual C ++ 2010 Express,我已经设置它所以它会编译C代码,但唯一不工作的是这个rand()函数。我试过包括一些通用的库,但没有什么工作。以下是代码:
So yeah, this might seem slightly noobish, but since I'm teaching myself C after becoming reasonable at Java, I've already run into some trouble. I'm trying to use the rand() function in C, but I can only call it once, and when it do, it ALWAYS generates the same random number, which is 41. I'm using Microsoft Visual C++ 2010 Express, and I already set it up so it would compile C code, but the only thing not working is this rand() function. I've tried including some generally used libraries, but nothing works. Here's the code:
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
int main(void)
{
printf("%d", rand()); //Always prints 41
return 0;
}
推荐答案
$ c> rand()始终从执行开始时的同一点初始化其伪随机序列。
This because the rand()
initializes its pseudo-random sequence always from the same point when the execution begins.
随机种子,然后使用 rand()
获取不同的值。这可以通过函数 srand
来完成,这将根据所传递的种子移动序列。
You have to input a really random seed before using rand()
to obtain different values. This can be done through function srand
that will shift the sequence according to the seed passed .
尝试: / p>
Try with:
srand(clock()); /* seconds since program start */
srand(time(NULL)); /* seconds since 1 Jan 1970 */
这篇关于rand()问题在C编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!