C++ if-else 如果

在 C++ 编程中,if 语句用于测试条件。C++ 中有多种类型的 if 语句。

  • if 语句

  • if-else 语句

  • 嵌套 if 语句

  • if-else-if 阶梯


C++ IF 语句

C++ if 语句测试条件。如果条件为真则执行。

句法 (Syntax)

if(condition){    
//code to be executed    
}



例子 (Example)

#include <iostream>  
using namespace std;  
   
int main () {  
   int num = 10;    
            if (num % 2 == 0)    
            {    
                cout<<"是偶数";    
            }   
   return 0;  
}

输出:

是偶数

C++ IF-else 语句

C++ if-else 语句也测试条件。如果条件为真则执行块,否则执行块。

例子 (Example)

if(condition){    
//如果条件为真,代码    
}else{    
//如果条件为假,代码   
}

例子 (Example)

#include <iostream>  
using namespace std;  
int main () {  
   int num = 11;    
            if (num % 2 == 0)    
            {    
                cout<<"是偶数";    
            }   
            else  
            {    
                cout<<"是奇数";    
            }  
   return 0;  
}

输出:

是奇数

C++ If-else 示例:来自用户的输入

例子 (Example)

#include <iostream>  
using namespace std;  
int main () {  
    int num;  
    cout<<"请输入一个数字:";  
    cin>>num;  
            if (num % 2 == 0)    
            {    
                cout<<"是偶数"<<endl;    
            }   
            else  
            {    
                cout<<"是奇数"<<endl;    
            }  
   return 0;  
}

输出:

输入数字:11
是奇数

输出:

输入一个数字:12
是偶数

C++ IF-else-if 梯形图语句

C++ if-else-if 梯形语句从多个语句中执行一个条件。

例子 (Example)

if(condition1){    
//条件1为真时执行的代码    
}else if(condition2){    
//条件2为真时执行的代码    
}    
else if(condition3){    
//条件3为真时执行的代码  
}    
...    
else{    
//所有条件为假时执行的代码    
}



C++ If else-if 示例

例子 (Example)

#include <iostream>  
using namespace std;  
int main () {  
       int num;  
       cout<<"输入一个数字来查看成绩:";    
       cin>>num;  
            if (num <0 || num >100)    
            {    
                cout<<"号码错误";    
            }    
            else if(num >= 0 && num < 50){    
                cout<<"失败";    
            }    
            else if (num >= 50 && num < 60)    
            {    
                cout<<"D 级";    
            }    
            else if (num >= 60 && num < 70)    
            {    
                cout<<"C 级";    
            }    
            else if (num >= 70 && num < 80)    
            {    
                cout<<"B 级";    
            }    
            else if (num >= 80 && num < 90)    
            {    
                cout<<"A 级";    
            }    
            else if (num >= 90 && num <= 100)    
            {    
                cout<<"A+ 级";  
            }    
    }

输出:

输入数字以查看等级:66
C级

输出:

输入一个数字以检查等级:-2
错号码


上一主题 没有了 下一主题 C++ switch 开关
  • 使用社交账号登录,本站支持
全部评论(0)