Latest web development tutorials

C ++ if ... else statement

C ++ judgment C ++ judgment

After aif statement with an optional else statement,else statement executes the Boolean expression is false.

grammar

C ++ syntax ofif ... else statement:

if(boolean_expression)
{
   // 如果布尔表达式为真将执行的语句
}
else
{
   // 如果布尔表达式为假将执行的语句
}

If the Boolean expression istrue, then the code ifthe execution block. If the Boolean expression isfalse, then the code within the elseblock executed.

flow chart

In C ++ if ... else statement

Examples

#include <iostream>
using namespace std;
 
int main ()
{
   // 局部变量声明
   int a = 100;
 
   // 检查布尔条件
   if( a < 20 )
   {
       // 如果条件为真,则输出下面的语句
       cout << "a 小于 20" << endl;
   }
   else
   {
       // 如果条件为假,则输出下面的语句
       cout << "a 大于 20" << endl;
   }
   cout << "a 的值是 " << a << endl;
 
   return 0;
}

When the above code is compiled and executed, it produces the following results:

a 大于 20
a 的值是 100

if ... else if ... else statement

After aif statement with an optional else if ... elsestatement, which can be used to test a variety of conditions.

When using if ... else if ... else statement, the following points should be noted:

  • Available with a zero or after a if else, else must after all else if.
  • If the latter can be followed by zero or more else if, else if necessary before else.
  • Once a successful match else if, else if or else the other will not be tested.

grammar

C ++ The syntax ofif ... else if ... else statement:

if(boolean_expression 1)
{
   // 当布尔表达式 1 为真时执行
}
else if( boolean_expression 2)
{
   // 当布尔表达式 2 为真时执行
}
else if( boolean_expression 3)
{
   // 当布尔表达式 3 为真时执行
}
else 
{
   // 当上面条件都不为真时执行
}

Examples

#include <iostream>
using namespace std;
 
int main ()
{
   // 局部变量声明
   int a = 100;
 
   // 检查布尔条件
   if( a == 10 )
   {
       // 如果 if 条件为真,则输出下面的语句
       cout << "a 的值是 10" << endl;
   }
   else if( a == 20 )
   {
       // 如果 else if 条件为真,则输出下面的语句
       cout << "a 的值是 20" << endl;
   }
   else if( a == 30 )
   {
       // 如果 else if 条件为真,则输出下面的语句
       cout << "a 的值是 30" << endl;
   }
   else
   {
       // 如果上面条件都不为真,则输出下面的语句
       cout << "没有匹配的值" << endl;
   }
   cout << "a 的准确值是 " << a << endl;
 
   return 0;
}

When the above code is compiled and executed, it produces the following results:

没有匹配的值
a 的准确值是 100

C ++ judgment C ++ judgment