位置:首頁 > 高級語言 > 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