2014-09-25 151 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