本帖最後由 葉桔良 於 2023-3-25 18:04 編輯
改寫 電費計算機 (一) 的程式碼,將所有 if...else 判斷的部分,以 switch...case 語法改寫。- #include<iostream>
- #include<cstdlib>
- #include<ctime>
- using namespace std;
- int main()
- {
- double month,dot;
- double sum=0;
-
- double w120=120*2.1;
- double w330=(330-120)*2.68;
- double w500=(500-330)*3.61;
- double w700=(700-500)*4.48;
- double w1000=(1000-700)*5.03;
-
- double s120=120*2.1;
- double s330=(330-120)*3.02;
- double s500=(500-330)*4.39;
- double s700=(700-500)*5.44;
- double s1000=(1000-700)*6.16;
-
- cout<<"***歡迎使用電費計算機***"<<endl<<endl;
- cout<<"請輸入月份: ";
- cin>>month;
- cout<<"用電度數: ";
- cin>>dot;
- if((month>=10&&month<=12)||(month>=1&&month<=5))
- {
- if(dot>=1001)
- sum=w1000+w700+w500+w330+w120+(dot-1000)* 5.28;
- else if(dot>=701)
- sum=w700+w500+w330+w120+(dot-700)* 5.03;
- else if(dot>=501)
- sum=w500+w330+w120+(dot-500)* 4.48;
- else if(dot>=331)
- sum=w330+w120+(dot-330)* 3.61;
- else if(dot>=121)
- sum=w120+(dot-120)* 2.68;
- else if(dot>=0)
- sum=dot* 2.1;
- }
- else if(month>=6&&month<=9)
- {
- if(dot>=1001)
- sum=s1000+s700+s500+s330+s120+(dot-1000)* 6.71;
- else if(dot>=701)
- sum=s700+s500+s330+s120+(dot-700)* 6.16;
- else if(dot>=501)
- sum=s500+s330+s120+(dot-500)* 5.44;
- else if(dot>=331)
- sum=s330+s120+(dot-330)* 4.39;
- else if(dot>=121)
- sum=s120+(dot-120)* 3.02;
- else if(dot>=0)
- sum=dot* 2.1;
- }
- cout<<endl<<"您要繳交的電費共:"<<sum<<"元"<<endl;
- system("pause");
- return 0;
- }
複製代碼 |