为什么每次编译和运行 rand() 都会得到相同的结果? [英] Why do I get the same result with rand() every time I compile and run?

查看:28
本文介绍了为什么每次编译和运行 rand() 都会得到相同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我运行此代码时,都会得到相同的结果.

Whenever I run this code, I get a same result.

程序

#include<stdlib.h>

int main(int agrc, const char *argv[]) {
 int i = rand();
 printf("%d
",i);
 for(i=0;i<10;i++) {
  printf("%d
",rand());
 }
}

结果:

41
18467
6334
26500
19169
15724
11478
29358
26962
24464
5705

我在 mingw 上运行了这个.其实我在学习Objective-C

I ran this on mingw. Actually I am learning Objective-C

请帮帮我.

推荐答案

在使用 rand 函数之前,您需要为其设置一个唯一编号.最简单的方法是使用 time()

You need to seed the rand function with a unique number before it can be used. The easiest method is to use time()

例如

srand(time(NULL));
rand();//now returns a random number

原因是 rand()(或任何其他基于算法的函数)提供的随机数不是随机的.rand 函数只是获取其当前的数值状态,应用转换,将转换结果保存为新状态并返回新状态.

The reason is that the random numbers provided by rand() (or any other algorithm based function) aren't random. The rand function just takes its current numerical state, applies a transformation, saves the result of the transformation as the new state and returns the new state.

所以为了让 rand 返回不同的伪随机数,你首先必须将 rand() 的状态设置为唯一的.

So to get rand to return different pseudo random numbers, you first have to set the state of rand() to something unique.

这篇关于为什么每次编译和运行 rand() 都会得到相同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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