C++运算符和表达式

算术运算符

C++提供了一系列算术运算符,用于执行基本的数学计算:

+:加法
-:减法
*:乘法
/:除法
%:取模(求余数)

示例代码:

#include <iostream>

int main() {
    int a = 10, b = 3;

    std::cout << "a + b: " << (a + b) << std::endl;
    std::cout << "a - b: " << (a - b) << std::endl;
    std::cout << "a * b: " << (a * b) << std::endl;
    std::cout << "a / b: " << (a / b) << std::endl;
    std::cout << "a % b: " << (a % b) << std::endl;

    return 0;
}

关系运算符

关系运算符用于比较值之间的关系,返回布尔值 true 或 false:

==:等于
!=:不等于
<:小于
>:大于
<=:小于等于
>=:大于等于


示例代码:

#include <iostream>

int main() {
    int a = 5, b = 3;

    std::cout << "a == b: " << (a == b) << std::endl;
    std::cout << "a != b: " << (a != b) << std::endl;
    std::cout << "a < b: " << (a < b) << std::endl;
    std::cout << "a > b: " << (a > b) << std::endl;
    std::cout << "a <= b: " << (a <= b) << std::endl;
    std::cout << "a >= b: " << (a >= b) << std::endl;

    return 0;
}

逻辑运算符

逻辑运算符用于组合和改变布尔表达式的值:

&&:逻辑与(and)
||:逻辑或(or)
!:逻辑非(not)


示例代码:

#include <iostream>

int main() {
    bool x = true, y = false;

    std::cout << "x && y: " << (x && y) << std::endl;
    std::cout << "x || y: " << (x || y) << std::endl;
    std::cout << "!x: " << !x << std::endl;

    return 0;
}

条件运算符(三元运算符)

条件运算符用于在一个表达式中进行条件判断,类似于简单的 if-else 语句:

condition ? expression_if_true : expression_if_false;

示例代码:

#include <iostream>

int main() {
    int a = 5, b = 3;

    int max = (a > b) ? a : b;

    std::cout << "Max value: " << max << std::endl;

    return 0;
}

网友评论0