C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ if-else

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

C++ IF语句

C++ if语句测试条件。条件为真时执行。
if(condition){  
//code to be executed  
}
Cpp如果不是1

如果是C++示例

#include <iostream>
using namespace std;
 
int main () {
   int num = 10;  
            if (num % 2 == 0)  
            {  
                cout<<"It is even number";  
            } 
   return 0;
}
输出:
It is even number

C++ IF-else语句

C++ if-else语句也测试条件。如果条件为true则执行block,否则执行block。
if(condition){  
//code if condition is true  
}else{  
//code if condition is false  
}  
Cpp如果不是2

C++ If-else示例

#include <iostream>
using namespace std;
int main () {
   int num = 11;  
            if (num % 2 == 0)  
            {  
                cout<<"It is even number";  
            } 
            else
            {  
                cout<<"It is odd number";  
            }
   return 0;
}
输出:
It is odd number

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

#include <iostream>
using namespace std;
int main () {
    int num;
    cout<<"Enter a Number: ";
    cin>>num;
            if (num % 2 == 0)  
            {  
                cout<<"It is even number"<<endl;  
            } 
            else
            {  
                cout<<"It is odd number"<<endl;  
            }
   return 0;
}
输出:
Enter a number:11
It is odd number
输出:
Enter a number:12
It is even number

C++ IF-else-if阶梯语句

C++ if-else-if阶梯语句从多个语句中执行一个条件。
if(condition1){  
//code to be executed if condition1 is true  
}else if(condition2){  
//code to be executed if condition2 is true  
}  
else if(condition3){  
//code to be executed if condition3 is true  
}  
...  
else{  
//code to be executed if all the conditions are false  
}  
Cpp如果不是3

C++ If else-if示例

#include <iostream>
using namespace std;
int main () {
       int num;
       cout<<"Enter a number to check grade:";  
       cin>>num;
            if (num <0 || num >100)  
            {  
                cout<<"wrong number";  
            }  
            else if(num >= 0 && num < 50){  
                cout<<"Fail";  
            }  
            else if (num >= 50 && num < 60)  
            {  
                cout<<"D Grade";  
            }  
            else if (num >= 60 && num < 70)  
            {  
                cout<<"C Grade";  
            }  
            else if (num >= 70 && num < 80)  
            {  
                cout<<"B Grade";  
            }  
            else if (num >= 80 && num < 90)  
            {  
                cout<<"A Grade";  
            }  
            else if (num >= 90 && num <= 100)  
            {  
                cout<<"A+ Grade";
            }  
    }  
输出:
Enter a number to check grade:66
C Grade
输出:
Enter a number to check grade:-2
wrong number

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4