使用什么来代替if/else、switch或三元运算符
what to use instead of if/else, switch or ternary operators?
只是一个快速问题。我有一个学校项目,我必须作为一个新的单独问题再次解决这个问题。只使用一行代码,不使用任何if/else或switch语句,也不使用三元运算符来提供税收计算。我可能可以在一行代码中进行计算,但如果要去掉条件语句,我不知道该写什么。下面是我应该更改的代码。我的老师对我们能用什么和不能用什么有点挑剔。此外,这个项目是在我们还没有学习这些函数的时候给我们的。我正在寻找一个不太高级别的答案,因为我是c++的新手。/***************************************************************
为一个根据税率表计算税款的州编写一个程序:•前15000美元收入免税•15001美元至25000美元每美元征收5%的税•25000美元以上每美元征收10%的税***************************************************************/
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
string income2;
double income;
const double FIRSTTAX = 500;
double secondDifference;
const double FTAX = 0.05;
const double TTAX = 0.1;
cout << "Please enter the annual income: $ ";
getline (cin, income2);
stringstream (income2)>> income;
if (income == 0 || income <= 15000 )
{
cout << "No income on first 15000 " << endl;
}
else if (income > 15000 && income <= 25000)
{
income = (income - 15000)* FTAX;
cout << " Your net income " << income <<endl;
}
else if (income > 25000)
{
secondDifference = (income - 25000) * TTAX +(income - 15000- (income - 25000)) * FTAX;
cout << " Your net income " << income <<fixed<<setprecision(2) <<endl;
cout << " Your tax " << secondDifference <<fixed<<setprecision(2) << endl;
}
return 0;
}
在一行中:
tax = max(income-15000,0)*FTAX + max(income-25000,0)*(TTAX-FTAX)
考虑两种不同的税率,并允许任何一种税率单独变化:
double lo_thresh = 15000;
double hi_thresh = 25000;
double lo_rate = 0.05;
double hi_rate = 0.10;
double tax = lo_rate * min(hi_thresh - lo_thresh, max(income - lo_thresh, 0)) +
hi_rate * max(income - hi_thresh, 0);
上半年的收入超过15000,但将超过该金额的金额上限为10000(即两个阈值之间的差额)。
下半年计算的是收入超过25000的更高税率。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 使用什么来代替if/else、switch或三元运算符
- 在 switch 语句中使用算术和逻辑运算符
- 在哪里可以找到如何用函数数组替换"switch"运算符的示例?
- 为什么我不能使用 ||OR C++ Switch 语句中的运算符?