INT_MIN的绝对值 [英] Absolute value of INT_MIN

查看:587
本文介绍了INT_MIN的绝对值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能提取不会溢出 INT_MIN 的绝对值?看到这个code的问题:

How could I extract the absolute value of INT_MIN without overflowing? See this code for the problem:

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    printf("INT_MAX: %d\n", INT_MAX);
    printf("INT_MIN: %d\n", INT_MIN);
    printf("abs(INT_MIN): %d\n", abs(INT_MIN));

    return 0;
}

吐出以下

INT_MAX: 2147483647
INT_MIN: -2147483648
abs(INT_MIN): -2147483648

我需要这个做了检查如果 INT 值大于零。

至于这个问题是一个重复<一个href=\"http://stackoverflow.com/questions/11243014/why-the-absolute-value-of-the-max-negative-integer-2147483648-is-still-2147483\">Why最大负整数-2147483648的绝对值仍-2147483648?,我不同意,因为这是一个怎么样,不是一个问题,为什么

As for this question being a duplicate of Why the absolute value of the max negative integer -2147483648 is still -2147483648?, I have to disagree, since this is a HOW, not a WHY question.

推荐答案

%d个中的格式字符串转换说明的printf 转换成相应的参数为有符号十进制整数,在这种情况下,溢出的 INT 键入。 C标准特别提到签署整数溢出是未定义的行为。你应该做的是在格式字符串使用%U 。此外,您还需要包含头文件 stdio.h中文件stdlib.h 的功能原型的printf ABS 分别。

The %d conversion specifier in the format string of printf converts the corresponding argument to a signed decimal integer, which in this case, overflows for the int type. C standard specifically mentions that signed integer overflow is undefined behaviour. What you should do is to use %u in the format string. Also, you need to include the headers stdio.h and stdlib.h for the prototype of the functions printf and abs respectively.

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

// This solves the issue of using the standard abs() function
unsigned int absu(int value) {
    return (value < 0) ? -((unsigned int)value) : (unsigned int)value;
}

int main(void) {
    printf("INT_MAX: %d\n", INT_MAX);
    printf("INT_MIN: %d\n", INT_MIN);
    printf("absu(INT_MIN): %u\n", absu(INT_MIN));

    return 0;
}

这给我的32位计算机上的输出:

This gives the output on my 32-bit machine:

INT_MAX: 2147483647
INT_MIN: -2147483648
abus(INT_MIN): 2147483648

这篇关于INT_MIN的绝对值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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