即使在不同的机器上,random或rand函数也会打印相同的值 [英] random or rand function prints the same value, even in different machines

查看:200
本文介绍了即使在不同的机器上,random或rand函数也会打印相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印一个1到6范围内的随机数.我有以下代码.

I want to print a random number in the range 1 to 6. I have the following code.

printf("The random value is %d \n",random(6));

每次运行代码时,它都会打印1804289383.即使在不同的机器上.我也试过rand(6)仍然输出相同.即使我删除了6,输出也不会改变.请建议如何解决

It is printing 1804289383 every time I run the code. Even on different machines. I also tried rand(6) still output is same. Even I removed 6, output does not change. Please suggest how to fix it

预先感谢

Sanket

推荐答案

您应该在rand()之前使用srand()来每次生成新数字.这段代码将显示如何做到这一点:

You shoud have srand() before rand() to generate new numbers each time. This code will show how do that:

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

int main()
{
    srand(time(0));
    printf("The random value is %d\n", 1 + rand() % 6);
    return 0;
}

这篇关于即使在不同的机器上,random或rand函数也会打印相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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