无符号整数

#include <iostream>
using namespace std;
int main()
{
    std::cout << "Hello World!\n";
    unsigned int x;
    unsigned int y = 96;
    unsigned int z = 69;
    x = z - y;
    cout << "The difference is:" << x << endl;
    x = y - z;
    cout << "Now the diffence is:" << x << endl;
    return 0;
}
 // --- 修正部分:展示如何正确处理可能为负的结果 ---
    // 方法1: 使用有符号整数
    {
        int signed_y = 96;
        int signed_z = 69;
        int signed_diff = signed_z - signed_y; // 结果可以是负数
        cout << "\n--- Using signed int ---" << endl;
        cout << "Signed difference (z - y) is: " << signed_diff << endl;
    }
    
    // 方法2: 在执行无符号减法前进行比较
    {
        cout << "\n--- Checking before unsigned subtraction ---" << endl;
        if (z >= y) {
            x = z - y;
            cout << "z - y = " << x << endl;
        } else {
            // 手动计算绝对值,并标记为负
            x = y - z;
            cout << "z - y = -" << x << " (or " << -(static_cast<int>(x)) << " as signed int)" << endl;
        }
        
        if (y >= z) {
            x = y - z;
            cout << "y - z = " << x << endl;
        } else {
            x = z - y;
            cout << "y - z = -" << x << " (or " << -(static_cast<int>(x)) << " as signed int)" << endl;
        }
    }
    
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务