这一章对操作符进行简单的总结:
1.五种基本运算类型:加减乘除,取余
add, substract, multiply, divide, modulus
int number1{2};
int number2{7};
int result = number1 + number2;
result = number2 - number1 ;
result = number1 - number2;
result = number1 * number2;
result = number2 / number1; // result:3
result = number2 % number1;
注意:两个int类型相除只会得到int类型的取整
2.优先级与结合性
https://en.cppreference.com/w/cpp/language/operator_precedence
3.前置和后置的++与--
后置的++/--先输出或者赋值原变量,之后再改变原变量
前置的++/--先改变原变量,再做改变后变量的赋值和输出
std::cout << "======Postfix increment and decrement======"<< std::endl;
value = 5;
std::cout << "The value is (incrementing) : " << value++ << std::endl; // 5
std::cout << "The value is : " << value << std::endl; // 6
std::cout << std::endl;
value = 5; //Reset value to 5
std::cout << "The value is (decrementing) : " << value-- << std::endl; //5
std::cout << "The value is : " << value << std::endl; // 4
std::cout << "======Prefix increment and decrement======"<< std::endl;
value = 5;
++value;
std::cout << "The value is (prefix++) : " << value << std::endl; // 6
value = 5;
std::cout << "The value is (prefix++ in place) : " << ++value << std::endl; // 6
std::cout << std::endl;
4.复合运算符
复合运算符同时完成运算和赋值的操作。
int value {45};
value +=5;
value -=5;
value *=2;
value /= 3;
value %= 11;
5.比较运算符
int number1 {20};
int number2 {20};
std::cout << std::boolalpha ; // Make bool show up as true/false instead of 1/0
//Stress the need for parentheses here
std::cout << "number1 < number2 : " << (number1 < number2) << std::endl;
std::cout << "number1 <= number2 : " << (number1 <= number2) << std::endl;
std::cout << "number1 > number2 : " << (number1 > number2) << std::endl;
std::cout << "number1 >= number2 : " << (number1 >= number2) << std::endl;
std::cout << "number1 == number2 : " << (number1 == number2) << std::endl;
std::cout << "number1 != number2 : " << (number1 != number2) << std::endl;
在输出比较结果的时候记得加上括号。<<的优先级高于比较运算符。
6.逻辑运算符
AND && 全真才真
OR || 一真即真
NOT !
这三个逻辑运算符联合使用记得优先级:NOT>AND>OR
bool a {true};
bool b {true};
bool c {false};
std::cout << std::boolalpha;
std::cout << (!a || b && c) << std::endl;
// !a: false, b && c: false, result: false
标签:value,优先级,int,C++,运算符,number2,result,number1 From: https://www.cnblogs.com/zspaiprogram/p/17894703.html