为什么INT I = 400 *四百分之四百给出结果72,是数据类型圆? [英] Why int i=400*400/400 gives result 72, is datatype circular?

查看:164
本文介绍了为什么INT I = 400 *四百分之四百给出结果72,是数据类型圆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得首先400 * 400 = 160000是从0开始,持续时间160000在一个圆形的时尚整型转换为28928(说的sizeof(int)的= 2个字节),假设它喜欢的:

I think first 400*400=160000 is converted to 28928 by starting from 0 and going 160000 time in a circular fashion for int type (say sizeof(int) = 2 bytes) assuming it like:

和然后28928是由400分,地板其中给出72,并将结果与​​变量的类型而变化。是我的假设是正确的,或有任何其他的解释吗?

And then 28928 is divided by 400, floor of which gives 72 and the result varies with the type of variable. Is my assumption correct or there is any other explanation?

推荐答案

假设你正在使用的是旧惊人,足够的编译器,其中 INT 仅在16位。然后是,你的分析是正确的。*

Assuming you're using a horrifically old enough compiler for where int is only 16 bits. Then yes, your analysis is correct.*

400 * 400 = 160000 

//  Integer overflow wrap-around.
160000 % 2^16 = 28928

//  Integer Division
28928 / 400 = 72 (rounded down)

当然,对于大型的数据类型,这种溢出不会发生,所以你会得到 400

*此环绕行为是有保障的仅适用于的符号的整数类型即可。对于有符号整数,这是技术上的未定义行为 C和C ++。

*This wrap-around behavior is guaranteed only for unsigned integer types. For signed integers, it is technically undefined behavior in C and C++.

在很多情况下,符号的整数仍然会表现出相同的环绕式的行为。 但是,你不能指望它。(所以带符号16位整数的例子并不保证持有。)

In many cases, signed integers will still exhibit the same wrap-around behavior. But you just can't count on it. (So your example with a signed 16-bit integer isn't guaranteed to hold.)

虽然罕见,但这里是哪里预期符号整数溢出不会环绕一些例子:

Although rare, here are some examples of where signed integer overflow does not wrap around as expected:

  • GCC Fail? Or Undefined Behavior?
  • Compiler optimization causing program to run slower

这篇关于为什么INT I = 400 *四百分之四百给出结果72,是数据类型圆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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