C++ if/else语句
在C++编程中,if语句用于测试条件。 在C++中有多种类型的if语句,它们分别如下所示 -
- if语句
- if-else语句
- 嵌套if语句
- if-else-if阶梯
1. C++ if语句
C++ if语句测试条件。 如果条件为真,则执行。
if(condition){
//code to be executed
}
C++ if语句的执行流程图如下所示 -
C++ if语句示例
#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
2. C++ if-else语句
C++if-else语句也测试条件。 如果if条件为真,则执行if块中的代码,否则执行else块中的代码。
if(condition){
//code if condition is true
}else{
//code if condition is false
}
if-else执行的流程如下图中所示 -
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;
}
执行上面代码得到以下结果 -
[codeinn@localhost cpp]$ g++ ifelse.cpp && ./a.out Enter a Number: 43 It is odd number [codeinn@localhost cpp]$ g++ ifelse.cpp && ./a.out Enter a Number: 22 It is even number [codeinn@localhost cpp]$
3. 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
}
if-else-if语句的执行流程如下图所示 -
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\n";
}
else if(num >= 0 && num < 50){
cout<<"Fail\n";
}
else if (num >= 50 && num < 60)
{
cout<<"D Grade\n";
}
else if (num >= 60 && num < 70)
{
cout<<"C Grade\n";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade\n";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade\n";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade\n";
}
return 0;
}
执行上面示例代码,得到以下结果 -
[codeinn@localhost cpp]$ g++ if-else-if.cpp && ./a.out Enter a number to check grade:99 A+ Grade [codeinn@localhost cpp]$ g++ if-else-if.cpp && ./a.out Enter a number to check grade:59 D Grade [codeinn@localhost cpp]$ g++ if-else-if.cpp && ./a.out Enter a number to check grade:49 Fail [codeinn@localhost cpp]$
本站文章除注明转载外,均为本站原创或编译
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动共创优秀实例教程
转载请注明:文章转载自:代码驿站 [http:/www.codeinn.net]
本文标题:C++ if/else语句
本文地址:http://www.codeinn.net/cplus/1719.html
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动共创优秀实例教程
转载请注明:文章转载自:代码驿站 [http:/www.codeinn.net]
本文标题:C++ if/else语句
本文地址:http://www.codeinn.net/cplus/1719.html


