本文介绍了为什么兰特()+兰特()产生负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我观察到兰特()当一个循环中调用只是一次库函数,它几乎总是产生正数。

I observed that rand() library function when it is called just once within a loop, it almost always produces positive numbers.

for (i = 0; i < 100; i++) {
    printf("%d\n", rand());
}

但是,当我添加两个兰特()通话,数字生成现在有更多的负数。

But when I add two rand() calls, the numbers generated now have more negative numbers.

for (i = 0; i < 100; i++) {
    printf("%d = %d\n", rand(), (rand() + rand()));
}

有人能解释我为什么在第二种情况中看到负数?

Can someone explain why I am seeing negative numbers in the second case?

PS:我的环路初始化前种子函数srand(时间(NULL))

PS: I initialize the seed before the loop as srand(time(NULL)).

推荐答案

兰特()被定义为返回之间的整数 0 RAND_MAX

rand() is defined to return an integer between 0 and RAND_MAX.

rand() + rand()

可能溢出。你观察到的可能是href=\"https://en.wikipedia.org/wiki/Undefined_behavior\">不确定的行为通过整数溢出引起

could overflow. What you observe is likely a result of undefined behaviour caused by integer overflow.

这篇关于为什么兰特()+兰特()产生负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 12:33