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
廣告