位置:首頁 > 高級語言 > C++教學 > C++ if...else語句

C++ if...else語句

if語句可以跟一個可選的else語句,該語句布爾表達式為假時執行。

語法

C++中if ... else語句的語法是:

if(boolean_expression)
{
   // statement(s) will execute if the boolean expression is true
}
else
{
  // statement(s) will execute if the boolean expression is false
}

if布爾表達式的值為true,那麼if代碼塊將被執行,否則else塊將執行。

流程圖:

C++ if...else statement

例如:

#include <iostream>
using namespace std;
 
int main ()
{
   // local variable declaration:
   int a = 100;
 
   // check the boolean condition
   if( a < 20 )
   {
       // if condition is true then print the following
       cout << "a is less than 20;" << endl;
   }
   else
   {
       // if condition is false then print the following
       cout << "a is not less than 20;" << endl;
   }
   cout << "value of a is : " << a << endl;
 
   return 0;
}

當上述代碼被編譯和執行時,它產生了以下結果:

a is not less than 20;
value of a is : 100

if...else if...else 語句:

if語句可以跟著一個可選的else if ... else語句,使用單個 if...else ,if語句是非常有用的,以測試各種條件。

使用if , else if , else語句有幾點要牢記。

  • 一個if可以有零或一個else,它必須跟從任何else if。

  • 一個if可以有零到多個else if,並且它們必須在else之前。

  • 一旦一個else if條件成功,其他剩餘else if不在計算,else將被測試。

語法

if...else if...else語句在C++ 語法是:

if(boolean_expression 1)
{
   // Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
   // Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
   // Executes when the boolean expression 3 is true
}
else 
{
   // executes when the none of the above condition is true.
}

例子:

#include <iostream>
using namespace std;
 
int main ()
{
   // local variable declaration:
   int a = 100;
 
   // check the boolean condition
   if( a == 10 )
   {
       // if condition is true then print the following
       cout << "Value of a is 10" << endl;
   }
   else if( a == 20 )
   {
       // if else if condition is true
       cout << "Value of a is 20" << endl;
   }
   else if( a == 30 )
   {
       // if else if condition is true 
       cout << "Value of a is 30" << endl;
   }
   else
   {
       // if none of the conditions is true
       cout << "Value of a is not matching" << endl;
   }
   cout << "Exact value of a is : " << a << endl;
 
   return 0;
}

讓我們編譯和運行上麵的程序,這將產生以下結果:

Value of a is not matching
Exact value of a is : 100