C++ if-else语句

C++ if-else语句 首页 / C++入门教程 / C++ if-else语句

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

  • if语句
  • if-else语句
  • 嵌套if语句
  • if-else-if语句

IF语句

C++ if语句条件判断,条件为真时执行。

if(condition){  
  //要执行的代码
}
Cpp If else 1
#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

IF-else语句

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

if(condition){  
  //条件为真时的代码
}else{  
  //条件为假时的代码
}  
Cpp If else 2
#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

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

#include 
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

IF-else-if 语句

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

if(condition1){  
  //条件1为真时执行的代码
}else if(condition2){  
  //条件2为真时执行的代码 
}  
else if(condition3){  
  //条件3为真时执行的代码
}  
...  
else{  
  //如果所有条件都为假,则要执行的代码 
}  
Cpp If else 3
#include <iostream>
using namespace std;
int main () {
       int num;
       cout<<"Enter a number to check grade:";  
       cin>>num;
            if (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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

邱岳的产品手记 -〔邱岳〕

微服务架构实战160讲 -〔杨波〕

玩转webpack -〔程柳锋〕

浏览器工作原理与实践 -〔李兵〕

Serverless入门课 -〔蒲松洋(秦粤)〕

Python自动化办公实战课 -〔尹会生〕

性能优化高手课 -〔尉刚强〕

如何讲好一堂课 -〔薛雨〕

Kubernetes入门实战课 -〔罗剑锋〕

好记忆不如烂笔头。留下您的足迹吧 :)