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

C++ , changing an if/else if into a switch statement

本文关键字:switch 语句 else-if if C++      更新时间:2023-10-16

C++问题-"编写一个程序,用他/她的父母的贡献计算学生的总储蓄。学生的父母同意根据学生使用下面给出的时间表节省的百分比添加到学生的储蓄中。"这是我用来计算父母贡献的if/else-if。我现在必须再次制作这个程序,除非使用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 

在这种情况下不能(不应该)这样做:switch仅对离散整数值有用。它对非平凡的范围没有用处,也不能直接与浮点一起使用。

无论如何,如果顺序颠倒,使得测试慢慢通过,那么大约一半的条件可以从if表达式中删除。。

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);