我很难为此问题创建循环。
计算所得税要求应用程序将所有先前税收范围内的所有税收累加到 收入的括号,如下表所示。 a)此外,您必须使用循环来解决此问题。
这是我到目前为止所拥有的
int[] upper = { 9525, 38700, 82500, 157500, 200000, 500000, };
int[] rate = { 10, 12, 22, 24, 32, 35, 37 };
double tax;
Write("Please enter your income >> ");
double income = Convert.ToInt32(ReadLine());
for (int i = 0; i < upper.Length; i++)
{
if (income <= upper[i])
{
tax = income * rate[i];
}
}
如果收入为100,000美元,则循环逻辑应该像这样
IncomeTax =
($ 9,525[upper[0]]) * 10%[rate[0]]
+ ($38,700[upper[1]] - $9,525[upper[0]]) * 12%[rate[1]]
+ ($82,500[upper[2]] - $38,700[upper[1]]) * 22%[rate[2]]
+ ($100,000[income] - $82,500[upper[2]]) * 24%[rate[3]] = $18,289.50[total]
任何帮助将不胜感激!
答案 0 :(得分:1)
这个小代码有太多问题。
income <= upper[i]
在此情况下不适合计算税金(upper[i] - upper[i -1])
上征税,而仅在upper[i]
上征税但是至少我可以看到您的努力,因此我发布了一个有效的代码供您参考(您可以进一步改进它)
//added , 9999999999 to make the last slab (37%) tends to infinite
long[] upper = { 9525, 38700, 82500, 157500, 200000, 500000, 9999999999 };
int[] rate = { 10, 12, 22, 24, 32, 35, 37 };
double tax = 0.0;
Console.WriteLine("Please enter your income >> ");
//if income is of double data type, we should convert console into double instead of int
double income = Convert.ToDouble(Console.ReadLine());
double taxCalculatedAmount = 0.0;
for (int i = 0; i < upper.Length; i++)
{
//Note: here I am calculating the delta
//which I will use to calculate the tax for the slab.
double incomeToCalculateTax =
upper[i] <= income ? (i == 0 ? upper[i] : upper[i] - upper[i - 1]) :
(i == 0 ? income : income - upper[i - 1]);
//Condition which will check if amount on which we have calculated tax is exceeding total amount
if (income > taxCalculatedAmount)
{
//proper formula of calculating tax
tax += (incomeToCalculateTax * rate[i]) / 100;
taxCalculatedAmount += incomeToCalculateTax;
}
else
break;
}
答案 1 :(得分:0)
以下是计算所需结果的自包含静态函数。尽管对于练习来说可能没有什么区别,但通常建议不要使用浮点数进行货币计算,因为在进行大量处理时可能会失去精度;要么转换为最低的单位(美分或其他),然后使用整数(或多头),或者使用小数,如下所示。
public static decimal IncomeTax(decimal income)
{
// Only positive income can be taxed
if (income <= 0M) return 0M;
// Initialize bracket limits and rate percentages
int[] brackets = { 0, 9525, 38700, 82500, 157500,
200000, 500000, int.MaxValue };
int[] rates = { 10, 12, 22, 24, 32, 35, 37 };
// Start with zero tax
decimal tax = 0M;
// Loop over tax rates and corresponding brackets
for (int i = 0; i < rates.Length; i++)
{
// Calculate amount of current bracket
int currBracket = brackets[i + 1] - brackets[i];
// If income is below lower bound, exit loop
if (income < brackets[i]) break;
// If income is between lower and upper bound,
if (income < brackets[i + 1])
{
// adjust bracket length accordingly
currBracket = income - brackets[i];
}
// Add tax for current bracket to accumulated tax
tax += (rates[i] / 100M) * currBracket;
}
// Return result
return tax;
}