为什么使用int错误,但是long long right
int c;
long long sum=0;
sum+=c*(c-1)/2;
当c=100000时,为什么sum得不到正确答案? 我应该写 sum+=(long long)(c*(c-1)/2);
int c;
long long sum=0;
sum+=c*(c-1)/2;
when c=100000,why sum can't get the right answer?
should I write
sum+=(long long)(c*(c-1)/2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
int
这里是 32 位,我假设 - 100000 平方 (10E9) 超出了int
的最大范围,导致溢出。下面的代码可行 - 将c
的第一个实例转换为long long
将意味着表达式的其余部分将是“long long 兼容”。int
here is 32-bit I assume - 100000 squared (10E9) exceeds the maximum range for anint
resulting in an overflow. The below would work - casting the first instance ofc
tolong long
will mean that the rest of the expression will be "long long compatible".因为它在计算中使用
c
作为int
,并在存储时将其加宽。在相乘之前,您需要将其中一个
c
转换为long long
。另外,我建议您考虑使用
int64_t
代替long long
,以便您无论如何都能获得所需的实际类型/大小(请参阅 stdint.h 用于各种标识符)。Because it is using
c
as anint
in the calculations, and widening it when it's stored.You need to cast one of the
c
's to along long
before multiplying.Also, I suggest you look into using
int64_t
in place oflong long
so that you can get the actual type/size you want no matter what (see stdint.h for the various identifiers).在你的问题中, c 被声明为整数。因此它跨越了表达式 c*(c-1) 中整数本身的限制。所以会发生溢出。在它被隐式转换为 long long 之前。这就是 UB 背后的原因。
而当你隐式地将其转换为 long long 时,你会得到正确的答案......
In your question c is declared as integer. so it crosses the limit of integer itself in the expression c*(c-1). so overflow occurs.before it gets implicitly converted into long long.Thats the reason behind UB.
whereas when u implicitly converted it into long long u will ger the right answer...