C++,将if/else-if更改为switch语句
C++ , changing an if/else if into a switch statement
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);
相关文章:
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 如何将 if else 语句重写为 switch 语句
- Switch 语句(字符串)一直选择默认值,除非其为零
- C++ switch 语句:对案例进行分组,并针对每个案例给出特定的说明
- 任意大小的 constexpr 数组是否可以用作 switch 语句中的案例?
- 默认标签显然在 switch 语句中不起作用
- C++如何在 switch 语句中放置两个参数
- 如何在 c++ 中从 switch 语句返回不同类型的变量
- 在编译时自动生成用于稀疏数组索引的switch语句
- C++ Switch 语句中的数学运算
- 变量不能在 lambda 中隐式捕获,并且没有使用 switch 语句指定捕获默认值
- 在任何案例之前,在 switch 语句中的使用声明是否合法?
- 使用 switch 语句将不同的函数作为类属性分配 C++
- 为什么我的 switch 语句没有响应一半的情况?
- 如何从映射中获取值并在 C++ 的 switch 语句中使用它
- switch 语句导致发送两条消息
- C++ Switch 语句在中断后执行
- switch语句,两种类似情况不同
- switch 语句和对象隐式 int 转换
- switch 语句结束和下一条语句之间的时间是否具有确定性(与路径无关)