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

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

问题描述

每当我运行此code,我得到了相同的结果。

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\n",i);
 for(i=0;i<10;i++) {
  printf("%d\n",rand());
 }
}

结果:

41
18467
6334
26500
19169
15724
11478
29358
26962
24464
5705

我跑这对的MinGW 。其实我在学习的Objective-C

请帮我。

推荐答案

您需要一个唯一的编号,以种子rand函数可以使用它。最简单的方法是使用 时间()

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函数只是需要其当前数值状态,应用转换,节约改造为新状态的结果,返回的新状态。

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()的状态设置为独一无二的东西。

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

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

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