【C++】error C4146: 一元负运算符应用于无符号类型,结果仍为无符号类型

刷leetcode 263.uglynumber时,代码如下:

class Solution {
public:
    bool isUgly(int num) {
        int temp = num;
        if (num == 1) return true;

        while (num>1){
            if (num % 2 == 0) num = num / 2;
            if (num % 3 == 0) num = num / 3;
            if (num % 5 == 0) num = num / 5;

            if (num == 1) return true;
            else if (num == temp) return false;

            temp = num;
        }
    }
};
int _tmain(int argc, _TCHAR* argv[])
{
    Solution solu;
    cout << solu.isUgly(-2147483648) << endl;

    system("pause"); 
    return 0;
}

测试用例里用到的数据是-2147483648,然后报错error C4146: 一元负运算符应用于无符号类型,结果仍为无符号类型

这是因为int的最小值是-2147483648,最大值是2147483647,但是我们不能用int n = -2147483648。因为编译器(VS2013)在看到int n = -2147483648;的时候,首先判断2147483648 > INT_MAX,知道int装不下,于是决定使用 unsigned int。然后发现前面还有个负号,于是对2147483648取反,然而取反操作实际上是将从高位到第一个1之间的位取反,+2147483648 : 10000000000000000000000000000000取反后依然是它本身。

 

参考:http://www.hankcs.com/program/cpp/error-c4146-%E4%B8%80%E5%85%83%E8%B4%9F%E8%BF%90%E7%AE%97%E7%AC%A6%E5%BA%94%E7%94%A8%E4%BA%8E%E6%97%A0%E7%AC%A6%E5%8F%B7%E7%B1%BB%E5%9E%8B%EF%BC%8C%E7%BB%93%E6%9E%9C%E4%BB%8D%E4%B8%BA%E6%97%A0.html

posted @ 2016-04-26 13:18  料峭  Views(5928)  Comments(0Edit  收藏  举报