C++ 操作符优先级
尝试下面的示例来理解C++中可用的操作符优先级的概念。将以下C++程序复制并粘贴到test.cpp文件中,然后编译并运行此程序。
通过使用和不使用括号来检查简单的差异。这将产生不同的结果,因为()
、/
、*
和+
具有不同的优先级。高优先级的操作符将首先计算。
#include <iostream>
using namespace std;
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
cout << "Value of (a + b) * c / d is :" << e << endl ;
e = ((a + b) * c) / d; // (30 * 15 ) / 5
cout << "Value of ((a + b) * c) / d is :" << e << endl ;
e = (a + b) * (c / d); // (30) * (15/5)
cout << "Value of (a + b) * (c / d) is :" << e << endl ;
e = a + (b * c) / d; // 20 + (150/5)
cout << "Value of a + (b * c) / d is :" << e << endl ;
return 0;
}
当上述代码被编译并执行时,会产生以下结果−
Value of (a + b) * c / d is :90
Value of ((a + b) * c) / d is :90
Value of (a + b) * (c / d) is :90
Value of a + (b * c) / d is :50