條件分支
無論是什么編程語言,都會有條件判斷,選擇分支,本講,將介紹條件判斷和選擇分支的使用。
1、if() else()型和if()
#include<iostream>
using namespace std;
const float pi = 3.14;
int main(){
int age = 18;
if (age < 18){
cout << "對不起,您未成年!" << endl;
}
else{
cout << "您已經是成年人!" << endl;
}
return 0;
}
Paste_Image.png
當age = 18時,不滿足if()條件,選擇else分支
Paste_Image.png
當age=18時,滿足條件,選擇if()分支
if()語句是if else的特例,這里省略了else,記住其實是有個else分支的,只是省略沒寫,因為這個分支什么都沒做。
2、if() else if() else if() ... else型
#include<iostream>
using namespace std;
const float pi = 3.14;
int main(){
int goal = 60;
cout << "goal = " << goal << endl;
if (goal <60 ){
cout << "對不起,不及格!" << endl;
}
else if (goal<80){
cout << "你獲得良!" << endl;
}
else{
cout << "很棒,你得了優秀!" << endl;
}
return 0;
}
Paste_Image.png
說明:if else類型的選擇語句是可以嵌套的,但是嵌套的時候要注意else的匹配問題,為了便于閱讀,盡量每個關鍵字后面都帶上括號{},沒有括號時,else與最近符if 匹配!!!
舉例說明:
#include<iostream>
using namespace std;
const float pi = 3.14;
int main(){
int day;
cout << "please input a number between 1 and 7: ";
cin >> day;
if (day < 6)
if (day == 1)
cout << "今天周一,是工作日" << endl;
else
cout << "今天是工作日,但不是周一,else與最近的if匹配" << endl;
return 0;
}
Paste_Image.png
3、switch()開關語句
當有多個類似的選擇分支時,通常使用switch語句進行選擇,使得代碼清晰明了,便于閱讀和理解。
例如輸入數字1-7,判斷對應的星期。
#include<iostream>
using namespace std;
const float pi = 3.14;
int main(){
int day;
cout << "please input a number between 1 and 7: ";
cin >> day;
switch (day){
case 1:cout << "今天是星期一!" << endl; break;
case 2:cout << "今天是星期二!" << endl; break;
case 3:cout << "今天是星期三!" << endl; break;
case 4:cout << "今天是星期四!" << endl; break;
case 5:cout << "今天是星期五!" << endl; break;
case 6:cout << "今天是星期六!" << endl; break;
default:cout << "今天是星期日!" << endl;
}
return 0;
}
Paste_Image.png
在switch語句中switch()括號中的值分別與case中的值比較,從相同的一項開始執行,break;跳出當前選擇,不然會一直執行,看下面代碼,比較不同。
#include<iostream>
using namespace std;
const float pi = 3.14;
int main(){
int day;
cout << "please input a number between 1 and 7: ";
cin >> day;
switch (day){
case 1:cout << "今天是星期一!" << endl; break;
case 2:cout << "今天是星期二!" << endl; break;
case 3:cout << "今天是星期三!" << endl;
case 4:cout << "今天是星期四!" << endl;
case 5:cout << "今天是星期五!" << endl;
case 6:cout << "今天是星期六!" << endl;
default:cout << "今天是星期日!" << endl;
}
return 0;
}
Paste_Image.png
因為case 3:之后的分支都沒有寫break;語句所以一直往后執行。實際操作中要注意!!!
在switch語句中default常常用來處理錯誤的情況,也就是未知的情況,但有時情況確定時可以作為其中一個情況分支使用。還有就是default要放在最后,以為switch中的值是從上往下依次比較的,并且default 的執行塊中不用再寫break;語句。