C中的rand()问题 [英] Problem with rand() in C

查看:130
本文介绍了C中的rand()问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么我总是得到与rand()相同的随机数序列?

Possible Duplicate:
why do i always get the same sequence of random numbers with rand() ?

这是到目前为止的文件:

This is my file so far:

#include <stdio.h>

int main(void) {
    int y;
    y = generateRandomNumber();
    printf("\nThe number is: %d\n", y);
    return 0;
}

int generateRandomNumber(void) {
    int x;
    x = rand();
    return x;
}

我的问题是rand()总是返回41.我在win上使用gcc ...不确定在这里做什么.

My problem is rand() ALWAYS returns 41. I am using gcc on win... not sure what to do here.

使用时间生成随机数将不起作用.它为我提供了一个数字(12000ish),每次我打电话时它都稍高一点(大约每秒+3).这不是我需要的随机性.我该怎么办?

Using time to generate a random number won't work. It provides me a number (12000ish) and every time I call it is just a little higher (about +3 per second). This isn't the randomness I need. What do I do?

推荐答案

标准技巧是:

srand(time(0));  // Initialize random number generator.

注意:该函数是srand,而不是rand.

NOTE: that function is srand, not rand.

在您的main函数中执行一次.之后,仅致电rand即可获取数字.

Do this once in your main function. After that, only call rand to get numbers.

根据实现的不同,它还可以帮助获取和丢弃rand的一些结果,以使序列与种子值不同.

Depending on the implementation, it can also help to get and discard a few results from rand, to allow the sequence to diverge from the seed value.

这篇关于C中的rand()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆