为什么 int 的范围是 -32768 到 32767? [英] Why the range of int is -32768 to 32767?

查看:54
本文介绍了为什么 int 的范围是 -32768 到 32767?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么任何数据类型的负数范围都比正数大?

例如,如果是整数:

Turbo C 中它的范围是 -3276832767 而对于 Visual Studio 它是 -21474836482147483647.

In Turbo C its range is -32768 to 32767 and for Visual Studio it is -2147483648 to 2147483647.

其他数据类型也是如此……

The same happens to other data types...

[UPD:为 Visual Studio 设置适当的限制值]

[UPD: Set proper limit values for Visual Studio]

推荐答案

因为数字的存储方式.带符号的数字是使用一种称为二进制补码"的东西存储的.

Because of how numbers are stored. Signed numbers are stored using something called "two's complement notation".

请记住,所有变量都有一定数量的位.如果其中最重要的一位是 0,则该数字是非负数(即正数或零),其余位仅表示该值.

Remember all variables have a certain amount of bits. If the most significant one of them, the one on the left, is a 0, then the number is non-negative (i.e., positive or zero), and the rest of the bits simply represent the value.

但是,如果最左边的位是 1,则该数字为负数.数字的真实值可以通过将表示的整数(作为无符号数,包括最左边的 1)减去 2^n 来获得,其中 n 是变量所具有的位数.

However, if the leftmost bit is a 1, then the number is negative. The real value of the number can be obtained by subtracting 2^n from the whole number represented (as an unsigned quantity, including the leftmost 1), where n is the amount of bits the variable has.

由于数字的实际值(尾数")只剩下 n - 1 位,因此可能的组合为 2^(n - 1).对于正数/零数,这很容易:它们从 0 变为 2^(n - 1) - 1.-1 是为了说明零本身——例如,如果你只有四种可能的组合,那些组合将代表 0、1、2 和 3(注意有四个数字):从 0 到 4 - 1.

Since only n - 1 bits are left for the actual value (the "mantissa") of the number, the possible combinations are 2^(n - 1). For positive/zero numbers, this is easy: they go from 0, to 2^(n - 1) - 1. That -1 is to account for zero itself -- for instance, if you only had four possible combinations, those combinations would represent 0, 1, 2, and 3 (notice how there's four numbers): it goes from 0 to 4 - 1.

对于负数,请记住最左边的位是 1,因此表示的整数介于 2^(n - 1) 和 (2^n) - 1 之间(括号在那里非常重要!).但是,正如我所说,您必须带走 2^n 才能获得数字的实际值.2^(n - 1) - 2^n 是 -(2^(n - 1)),并且 ((2^n) - 1) - 2^n 是 -1.因此,负数的范围是 -(2^(n - 1)) 到 -1.

For negative numbers, remember the leftmost bit is 1, so the whole number represented goes between 2^(n - 1) and (2^n) - 1 (parentheses are very important there!). However, as I said, you have to take 2^n away to get the real value of the number. 2^(n - 1) - 2^n is -(2^(n - 1)), and ((2^n) - 1) - 2^n is -1. Therefore, the negative numbers' range is -(2^(n - 1)) to -1.

将所有这些放在一起,您会得到 -2^(n - 1) 到 2^(n - 1) - 1.如您所见,上限得到 -1,而下限没有.

Put all that together and you get -2^(n - 1) to 2^(n - 1) - 1. As you can see, the upper bound gets a -1 that the lower bound doesn't.

这就是为什么负数比正数多一个.

And that's why there's one more negative number than positive.

这篇关于为什么 int 的范围是 -32768 到 32767?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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