Show 例子
优质
小牛编辑
130浏览
2023-12-01
尝试以下示例以了解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