使用位操作符判断两个整数是否异号

sign.cpp内容如下:

#include <iostream>
using namespace std;

bool opposite_sign(int a, int b)
{
    return ((a ^ b) < 0);
}

int main(int argc, char **argv)
{
    int a = 1, b = 2, c = -3;
    if (opposite_sign(a, b))
        cout << a << " and " << b << " are of opposite sign" << endl;
    else
        cout << a << " and " << b << " are of same sign" << endl;
    if (opposite_sign(a, c))
        cout << a << " and " << c << " are of opposite sign" << endl;
    else
        cout << a << " and " << c << " are of same sign" << endl;

    return 0;
}

运行结果如下:

posted @ 2020-07-29 15:40  jackie_astro  阅读(249)  评论(0编辑  收藏  举报