本帖最後由 葉桔良 於 2022-9-24 17:30 編輯
改寫 電費計算機 (一) 的程式碼,將所有 if...else 判斷的部分,以 switch...case 語法改寫。
參考[作業] switch 判斷式 (五)- #include<iostream>
- #include<cstdlib>
- #include<ctime>
- using namespace std;
- int main()
- {
- re:
- int month, dot;
- double s_d120,s_d330,s_d500,s_d700,s_d1000;
- double w_d120,w_d330,w_d500,w_d700,w_d1000;
- double sum=0.0;
-
- w_d120=(120-0)*2.1;
- w_d330=(330-120)*2.68;
- w_d500=(500-330)*3.61;
- w_d700=(700-500)*4.48;
- w_d1000=(1000-700)*5.03;
-
- s_d120=(120-0)*2.1;
- s_d330=(330-120)*3.02;
- s_d500=(500-330)*4.39;
- s_d700=(700-500)*5.44;
- s_d1000=(1000-700)*6.16;
-
-
- cout<<"***歡迎使用小米電費計算機***"<<endl<<endl;
- cout<<"請輸入月份:";
- cin>>month;
- cout<<"用電度數:";
- cin>>dot;
- switch(month)
- {
- case 1 ... 5:
- case 10 ... 12:
- switch(dot)
- {
- case 1001 ... 10000:
- sum=w_d120 + w_d330 + w_d500 + w_d700 + w_d1000 + (dot-1000)*5.28;
- break;
- case 701 ... 1000:
- sum=w_d120 + w_d330 + w_d500 + w_d700 + (dot-700)*5.03;
- break;
- case 501 ... 700:
- sum=w_d120 + w_d330 + w_d500 + (dot-500)*4.48;
- break;
- case 331 ... 500:
- sum=w_d120 + w_d330 + (dot-330)*3.16;
- break;
- case 121 ... 330:
- sum=w_d120 + (dot-120)*2.68;
- break;
- case 1 ... 120:
- sum=(dot)*2.1;
- break;
- }
- break;
- case 6 ... 9:
- switch(dot)
- {
- case 1001 ... 10000:
- sum=s_d120 + s_d330 + s_d500 + s_d700 + s_d1000 + (dot-1000)*6.71;
- break;
- case 701 ... 1000:
- sum=s_d120 + s_d330 + s_d500 + s_d700 + (dot-700)*6.16;
- break;
- case 501 ... 700:
- sum=s_d120 + s_d330 + s_d500 + (dot-500)*5.44;
- break;
- case 331 ... 500:
- sum=s_d120 + s_d330 + (dot-330)*4.39;
- break;
- case 121 ... 330:
- sum=s_d120 + (dot-120)*3.02;
- break;
- case 1 ... 120:
- sum=(dot)*2.1;
- break;
- }
- break;
- }
- cout<<"您要繳的電費共:"<<sum<<endl;
- goto re;
- system("pause");
- }
複製代碼 |