为什么兰特()总是返回相同的值? [英] Why does rand() always return the same value?

查看:92
本文介绍了为什么兰特()总是返回相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  生成用C 结果随机数
  使用兰特产生

我试图来产生随机数,但我不断得到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;
}

这篇关于为什么兰特()总是返回相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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