位置:首页 > 高级语言 > C++在线教程 > C++运算符优先级

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