2014-09-25 155 views
-2

C++ question-「編寫一個程序,用於計算學生父母的貢獻總額,學生的父母同意增加學生的儲蓄學生使用下面給出的時間表保存的百分比「如果我用來查明父母的貢獻,這是if/else。除了使用switch語句之外,我現在必須再次創建該程序。我不知道如何做到這一點。用戶輸入總收入和他決定放棄的金額。 (我的課程剛剛開始,所以我必須用很簡單的方法來做到這一點謝謝)這是第一個版本:C++,將if/else改爲switch語句

percent_saved = money_saved/money_earned;   // calculates the percent of how much was saved 

if (percent_saved <.05)        // this if/else if statement assigns the parents percentage of contribution to their students saving 
{ 
    parents = .01; 
} 
else if (percent_saved >= .05 && percent_saved < .1) 
{ 
    parents = .025; 
} 
else if (percent_saved >= .1 && percent_saved < .15) 
{ 
    parents = .08; 
} 
else if (percent_saved >= .15 && percent_saved < .25) 
{ 
    parents = .125; 
} 
else if (percent_saved >= .25 && percent_saved < .35) 
{ 
    parents = .15; 
} 
else 
{ 
    parents = .2; 
} 

parentsmoney = parents*money_earned;     // using the correct percentage, this creates the amount of money parents will contribute 
total_savings = parentsmoney + money_saved;   // this adds together the parent's contribution and the student's savings 

回答

3

這不能(也不應該)被在這種情況下完成的:switch只有用於離散整數值。它是not useful for non-trivial ranges and cannot be used directly with floats

總之,大約有一半的判斷條件可以從如果表達式被刪除,如果順序顛倒,使得測試通過.. inchworm'ed現在

if (percent_saved >= .35) { 
    parents = .2; 
} else if (percent_saved >= .25) { 
    parents = .15; 
} // etc. 

,如果要求是「使用開關語句「(愚蠢的家庭作業問題),然後考慮首先將浮點值標準化爲」桶「,使得0.05 => 1,0.1 => 2,0.15 => 3等。然後可以在相關案件(有些案件屬於透明案件),如相關問題所示。

int bucket = rint(percent_saved/0.05); 
+0

+1,因爲這是一個很好的合理答案。 – 2014-09-25 00:54:46