本帖最後由 鄭繼威 於 2023-4-8 13:41 編輯
改寫 電費計算機 (一) 的程式碼,將所有 if...else 判斷的部分,以switch 判斷式 (二)&switch 判斷式 (四)語法改寫。- #include<iostream>
- #include<cstdlib>
- using namespace std;
- int main()
- {
- int m,d;
- float p;
- cout<<"***歡迎使用小米的電費計算機***"<<endl<<endl;
- cout<<"請輸入月份: ";
- cin>>m;
- cout<<"用電度數: ";
- cin>>d;
- //判斷是不是夏季
- switch(m)
- {
- //非夏季
- case 1 ... 5:
- case 10 ... 12:
- switch(d)
- {
- case 1001 ... 5000:
- p=120*2.1+(330-120)*2.68+(500-330)*3.61+(700-500)*4.48+(1000-700)*5.03+(d-1000)*5.28;
- break;
- case 701 ... 1000:
- p=120*2.1+(330-120)*2.68+(500-330)*3.61+(700-500)*4.48+(d-700)*5.03;
- break;
- case 501 ... 700:
- p=120*2.1+(330-120)*2.68+(500-330)*3.61+(d-500)*4.48;
- break;
- case 331 ... 500:
- p=120*2.1+(330-120)*2.68+(d-330)*3.61;
- break;
- case 121 ... 330:
- p=120*2.1+(d-120)*2.68;
- break;
- case 1 ... 120:
- p=d*2.1;
- break;
- }
- break;
- //夏季
- case 6 ... 9:
- switch(d)
- {
- case 1001 ... 5000:
- p=120*2.1+(330-120)*3.02+(500-330)*4.39+(700-500)*5.44+(1000-700)*6.16+(d-1000)*6.71;
- break;
- case 701 ... 1000:
- p=120*2.1+(330-120)*3.02+(500-330)*4.39+(700-500)*5.44+(d-700)*6.16;
- break;
- case 501 ... 700:
- p=120*2.1+(330-120)*3.02+(500-330)*4.39+(d-500)*5.44;
- break;
- case 331 ... 500:
- p=120*2.1+(330-120)*3.02+(d-330)*4.39;
- break;
- case 121 ... 330:
- p=120*2.1+(d-120)*3.02;
- break;
- case 1 ... 120:
- p=d*2.1;
- break;
- }
- break;
- }
- cout<<endl<<"您要繳交的電費共: "<<p<<"元!"<<endl;
- system("pause");
- return 0;
- }
複製代碼 |