本帖最後由 tonyh 於 2013-12-14 15:20 編輯
將今天上課寫的程式碼改寫,
移除 switch...case 敘述, 全部用 if...else if...else 取代.- #include<iostream>
- #include<cstdlib>
- using namespace std;
- int main()
- {
- int m,d,cost;
- cout<<"***歡迎使用小米的電費計算機***"<<endl<<endl;
- re1:
- cout<<"請輸入月份: ";
- cin>>m;
- re2:
- if(m>=6 && m<=9)
- {
- cout<<"用電度數: ";
- cin>>d;
- if(d>0 && d<=120)
- cost=2.1*d;
- else if(d>=121 && d<=330)
- cost=2.1*120+3.02*(d-120);
- else if(d>=331 && d<=500)
- cost=2.1*120+3.02*(330-120)+4.39*(d-330);
- else if(d>=501 && d<=700)
- cost=2.1*120+3.02*(330-120)+4.39*(500-330)+4.97*(d-500);
- else if(d>700)
- cost=2.1*120+3.02*(330-120)+4.39*(500-330)+4.97*(700-500)+5.63*(d-700);
- else
- {
- cout<<"用電度數輸入錯誤!"<<endl;
- goto re2;
- }
- }else if((m>=10 && m<=12) || (m>=1 && m<=5))
- {
- cout<<"用電度數: ";
- cin>>d;
- if(d>0 && d<=120)
- cost=2.1*d;
- else if(d>=121 && d<=330)
- cost=2.1*120+2.68*(d-120);
- else if(d>=331 && d<=500)
- cost=2.1*120+2.68*(330-120)+3.61*(d-330);
- else if(d>=501 && d<=700)
- cost=2.1*120+2.68*(330-120)+3.61*(500-330)+4.01*(d-500);
- else if(d>700)
- cost=2.1*120+2.68*(330-120)+3.61*(500-330)+4.01*(700-500)+4.5*(d-700);
- else
- {
- cout<<"用電度數輸入錯誤!"<<endl;
- goto re2;
- }
- }else
- {
- cout<<"月份輸入錯誤!"<<endl;
- goto re1;
- }
- cout<<endl<<"您要繳交的電費共: "<<cost<<"元!"<<endl<<endl;
- system("pause");
- return 0;
- }
複製代碼 |