今日課程重點:
- ASCII 碼與英文字母的轉換。
- switch 迴圈
- 其它迴圈的練習
課堂練習題目:
1. 透過ascii 碼來顯示字母。
程式碼:
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void){
//用ascii顯示英文字母
//char character = 97;
// A~Z is 65~90, a~z is 97~122
char type = 66; //設定字元的 ascii
cout << type << endl;
char types = 'D';
cout << (int)types << endl; //顯示字母的ascii碼
system("pause");
return 0;
}
2. 讓使用者輸入ascii 十進位碼,顯示對應的文字。
程式碼:
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void){
int x;
cout << "請輸入一個數字" << endl;
cin >> x;
cout << (char)x << endl;
system("pause");
return 0;
}
3. 利用 for迴圈列印 A~Z
程式碼:
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void){
//用ascii顯示英文字母
//char character = 97;
// A~Z is 65~90, a~z is 97~122
for(int i=65; i<=90; i++){
char character = i; //ascii 編碼
cout << character << endl;
}
system("pause");
return 0;
}
4. 編寫一程式,由使用者輸入 height(公尺) 與 weight,分別代表使用者的身高與體重,並且完成下列問題。
1. 利用BMI = weight(m) / height(kg)^2 計算此人的BMI值。
2. 判斷使用者是否過重。當範圍在 18.5 <= BMI < 24 為顯示為正常,超出則為過重,小於為過輕。
程式碼:
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void){
float height;
float weight;
float bmi;
cout << "請輸入身高(cm) : " << endl;
cin >> height;
height = height / 100; //轉換成公尺
cout << "請輸入體重 : " << endl;
cin >> weight;
bmi = weight / (height * height);
cout << "您的BMI值為 : ";
cout << bmi << endl;
if(bmi < 18.5){
cout << "要多吃一點喔,您的體重過輕了!!" << endl;
}else if(bmi > 24){
cout << "請注意,您的體重有點過重喔!!" << endl;
}else{
cout << "恭喜您為標準體重!" << endl;
}
system("pause");
return 0;
}
5. 某大賣場的促銷折扣方案為:
- 購物滿 1000元,打95折
- 購物滿 3000~4999元,打92折
- 購物滿 5000~9999元,打9折
- 購物滿 10000元,打8折
- 試編寫一程式計算消費者應付的金額。
程式碼:
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void){
int price;
cout << "請輸入金額" << endl;
cin >> price;
if(price <= 1000){
cout << "您購買金額為" << price << "可以打九五折," << endl;
cout << "您的應付金額為" << (float)price*0.95 << endl;
}else if(price < 5000){
cout << "您購買金額為" << price << "可以打九二折," << endl;
cout << "您的應付金額為" << (float)price*0.92 << endl;
}else if(price < 10000){
cout << "您購買金額為" << price << "可以打九折," << endl;
cout << "您的應付金額為" << (float)price*0.9 << endl;
}else if(price > 10000){
cout << "您購買金額為" << price << "可以打八折," << endl;
cout << "您的應付金額為" << (float)price*0.8 << endl;
}
system("pause");
return 0;
}
留言列表