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
cpp_operators.htm
广告