120 likes | 370 Views
C++ 程式設計入門. 條件判斷 if –else switch 作者:黃建庭. 程式的三個主要結構. 循序結構 選擇結構 ( 本單元 ) 重複結構. 條件判斷. 若測式條件成立,則執行條件成立的動作,否則執行條件不成立的動作」 例如: 若明天天氣很好的話,我們就去動物園,否則就待在家裡. 單向選擇結構 語法 if. 範例 - 及格判斷. #include <iostream> using namespace std; int main(){ int score; cin >> score; if (score > 60){
E N D
C++程式設計入門 條件判斷if –else switch 作者:黃建庭
程式的三個主要結構 • 循序結構 • 選擇結構(本單元) • 重複結構
條件判斷 • 若測式條件成立,則執行條件成立的動作,否則執行條件不成立的動作」 • 例如:若明天天氣很好的話,我們就去動物園,否則就待在家裡
範例-及格判斷 #include <iostream> using namespace std; int main(){ int score; cin >> score; if (score > 60){ cout << "很好,請繼續保持下去" << endl; } system("pause"); }
雙向選擇結構範例-超過2000打九折 #include <iostream> using namespace std; int main(){ int cost; cin >> cost; if (cost >= 2000){ cout << cost*0.9 << endl; }else{ cout << cost << endl; } system("pause"); }
多向選擇─使用if-else語法-分數與評語 #include <iostream> using namespace std; int main(){ int score; cout << "請輸入一成績?"; cin >> score; if (score >= 80) { cout << "非常好" << endl; }else if (score >= 60) { cout << "不錯喔" << endl; }else { cout << "要加油" << endl; } system("pause"); }
多向選擇範例─使用Switch-Case switch (iBMI){ case 1 ... 17: cout << "體重過輕" << endl; break; case 18 ... 23: cout << "體重正常" << endl; break; case 24 ... 26: cout << "體重過重" << endl; break; default: cout << "體重肥胖" << endl; break; } system("pause"); } #include <iostream> #include <math.h> using namespace std; int main(){ double weight,height,BMI; int iBMI; cout << "請輸入體重(KG)?"; cin >> weight; cout << "請輸入體重(M)?"; cin >> height; BMI=weight/(height*height); cout << "BMI為" << BMI << endl; iBMI=floor(BMI);