C ++,将if / else if更改为switch语句

时间:2014-09-25 00:38:39

标签: c++ if-statement switch-statement

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 

1 个答案:

答案 0 :(得分:3)

在这种情况下,不能(不应该)完成:switch 离散整数值有用。它是not useful for non-trivial ranges and cannot be used directly with floats

无论如何,如果排序反转,大约一半的条件可以从if表达式中删除,以便测试是通过..尺寸的。

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

现在,如果要求是&#34;请使用switch语句&#34; (愚蠢的家庭作业问题),然后考虑首先将浮动值标准化为&#34;桶&#34;使得0.05 =&gt; 1,0.1 =&gt; 2,0.15 =&gt;然后可以在相关的情况下检查得到的整数(在某些情况下是直通),如链接问题所示。

int bucket = rint(percent_saved / 0.05);