为什么rand()+ rand()产生负数?

本文翻译自:Why does rand() + rand() produce negative numbers?

I observed that rand() library function when it is called just once within a loop, it almost always produces positive numbers. 我观察到rand()库函数在循环中只调用一次,它几乎总是产生正数。

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. 但是当我添加两个rand()调用时,现在生成的数字会有更多的负数。

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: I initialize the seed before the loop as srand(time(NULL)) . PS:我在循环之前将种子初始化为srand(time(NULL))


#1楼

参考:https://stackoom.com/question/25K3S/为什么rand-rand-产生负数


#2楼

rand() is defined to return an integer between 0 and RAND_MAX . rand()定义为返回0RAND_MAX之间的整数。

rand() + rand()

could overflow. 可能会溢出 What you observe is likely a result of undefined behaviour caused by integer overflow. 您观察到的可能是整数溢出导致的未定义行为的结果。


#3楼

The problem is the addition. 问题是增加。 rand() returns an int value of 0...RAND_MAX . rand()返回一个int<

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值