📅  最后修改于: 2023-12-03 15:29:55.622000             🧑  作者: Mango
C++中常用的运算符有算术运算符、关系运算符、逻辑运算符、位运算符、赋值运算符、条件运算符等,下面我们分别来介绍一下它们的用法和注意事项。
C++中常用的算术运算符包括加、减、乘、除和取模,分别用+、-、*、/和%表示。其中%表示取模运算,用于得到两个数相除的余数。
// 算术运算符示例
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 3;
cout << "a + b = " << a+b << endl;
cout << "a - b = " << a-b << endl;
cout << "a * b = " << a*b << endl;
cout << "a / b = " << a/b << endl;
cout << "a % b = " << a%b << endl;
return 0;
}
注意事项:
C++中的关系运算符用于比较两个值的大小关系,返回的结果是bool类型的,可以是真(true)或假(false)。常用的关系运算符包括大于、小于、等于、大于等于、小于等于和不等于,分别用>、<、==、>=、<=和!=表示。
// 关系运算符示例
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 3;
cout << "a > b is " << (a > b) << endl;
cout << "a < b is " << (a < b) << endl;
cout << "a == b is " << (a == b) << endl;
cout << "a >= b is " << (a >= b) << endl;
cout << "a <= b is " << (a <= b) << endl;
cout << "a != b is " << (a != b) << endl;
return 0;
}
注意事项:
C++中的逻辑运算符用于将两个或多个bool值进行运算,返回的结果也是bool类型的。常用的逻辑运算符包括与、或、非,分别用&&、||和!表示。
// 逻辑运算符示例
#include <iostream>
using namespace std;
int main() {
bool a = true, b = false;
cout << "a && b is " << (a && b) << endl;
cout << "a || b is " << (a || b) << endl;
cout << "!a is " << !a << endl;
return 0;
}
注意事项:
C++中的位运算符用于对二进制数进行操作,常用的位运算符包括按位与、按位或、按位异或、左移和右移,分别用&、|、^、<<和>>表示。
// 位运算符示例
#include <iostream>
using namespace std;
int main() {
int a = 0b1100, b = 0b1010;
cout << "a & b = " << (a & b) << endl;
cout << "a | b = " << (a | b) << endl;
cout << "a ^ b = " << (a ^ b) << endl;
cout << "a << 1 = " << (a << 1) << endl;
cout << "b >> 1 = " << (b >> 1) << endl;
return 0;
}
注意事项:
C++中的赋值运算符用于将一个值赋给一个变量,常用的赋值运算符包括=、+=、-=、*=、/=、%=、&=、|=、^=、<<=和>>=,分别表示赋值、加法赋值、减法赋值、乘法赋值、除法赋值、取模赋值、按位与赋值、按位或赋值、按位异或赋值、左移赋值和右移赋值。
// 赋值运算符示例
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 3;
a += b;
cout << "a += b is " << a << endl;
a -= b;
cout << "a -= b is " << a << endl;
a *= b;
cout << "a *= b is " << a << endl;
a /= b;
cout << "a /= b is " << a << endl;
a %= b;
cout << "a %= b is " << a << endl;
a &= b;
cout << "a &= b is " << a << endl;
a |= b;
cout << "a |= b is " << a << endl;
a ^= b;
cout << "a ^= b is " << a << endl;
a <<= 1;
cout << "a <<= 1 is " << a << endl;
a >>= 1;
cout << "a >>= 1 is " << a << endl;
return 0;
}
注意事项:
C++中的条件运算符用于进行条件判断,常用形式为 (condition) ? true_value : false_value,当condition为真时返回true_value,否则返回false_value。
// 条件运算符示例
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 3;
string s = (a > b) ? "a > b" : "a <= b";
cout << s << endl;
return 0;
}
注意事项: