为什么最大负整数-2147483648的绝对值仍-2147483648? [英] Why the absolute value of the max negative integer -2147483648 is still -2147483648?

查看:742
本文介绍了为什么最大负整数-2147483648的绝对值仍-2147483648?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ABS的结果(-2147483648)是-2147483648,不是吗?
这似乎是不可接受的。

 的printf(ABS(-2147483648):%d个\\ N,ABS(-2147483648));

输出:

  ABS(-2147483648):-2147483648


解决方案

标准说,关于 ABS()

的ABS,实验室和llabs函数计算整数j的绝对值。如果
结果不能再presented,行为是不确定的。

和的结果确实不能重新presented因为2的补重新$ P $符号整数的psentation是不对称的。想想看......如果你在32位的 INT ,也为您提供了2 32 INT_MIN不同的值 INT_MAX 。这是一个偶数值。所以,如果有只有一个0,​​值大于0的数字不能是相同的值数小于0。所以没有积极对口 INT_MIN 与值 - INT_MIN

那么,什么是不能接受的是呼吁 ABS(INT_MIN)您的平台。

The result of abs(-2147483648) is -2147483648, isn't it? it seems unacceptable.

printf("abs(-2147483648): %d\n", abs(-2147483648));

output:

abs(-2147483648): -2147483648

解决方案

The standard says about abs():

The abs, labs, and llabs functions compute the absolute value of an integer j. If the result cannot be represented, the behavior is undefined.

And the result indeed cannot be represented because the 2's complement representation of signed integers isn't symmetric. Think about it... If you have 32 bits in an int, that gives you 232 distinct values from INT_MIN to INT_MAX. That's an even number of values. So, if there's only one 0, the number of values greater than 0 cannot be the same as the number of values less than 0. And so there's no positive counterpart to INT_MIN with a value of -INT_MIN.

So, what's unacceptable is calling abs(INT_MIN) on your platform.

这篇关于为什么最大负整数-2147483648的绝对值仍-2147483648?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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