0

我有这段代码可以计算员工工资的月税。当我运行它时,一切似乎都运行良好,直到 if 子句中的点。

如果我将 basicSalary 提供为 50000 并将所有其他输入值提供为 0,那么当应在 4000 左右时,monthlyTax 数字会变为零。

谁能解释我为什么会这样?

#include <stdio.h>

int main()
{
    int basicSalary, allowances, transportAllowance, numberOfDependants, deduction;
    float monthlyTax, income;

    printf("Enter Basic Salary Amount: ");
    scanf("%d", &basicSalary);

    printf("\nEnter Allowances Amount: ");
    scanf("%d", &allowances);

    printf("\nEnter transportAllowance Amount: ");
    scanf("%d", &transportAllowance);

    printf("\nEnter Number Of Dependants: ");
    scanf("%d", &numberOfDependants);

    switch (numberOfDependants)
    {
           case 0:
                deduction = 215000;
                break;
           case 1:
                deduction = 325000;
                break;
           case 2:
                deduction = 415000;
                break;
           case 3:
                deduction = 475000;
                break;
           default:
                   printf("Number Of Dependants Can Only Be Between 0 - 3, Enter A Proper Value.");
                   return 1;
    }

    income = basicSalary * 13 + allowances + (transportAllowance - 6800) * 12 - deduction;

    if (income < 500000)
    {
        monthlyTax = ((15/100) * (income/12));
    }
    else
    {  
        monthlyTax = ((15/100) * (500000/12)) + ((30/100) * ((income-500000)/12));
    }

    monthlyTax = monthlyTax/12;

    printf("\nMothly Tax Amount is %f", monthlyTax);
    getch();

    return 0;
}
4

2 回答 2

6

在 C 中,15 / 100等于0,因为它是整数除法

原作者的意思大概是浮点除法15.0 / 100.0

一般来说,浮点计算中隐含的所有常量也应该是浮点类型的(即,有.0附加的),除非你真的知道你在做什么。为了安全起见,这适用于所有数字,而不仅仅是部门中的数字。

如果它们不是常量而是整数变量,则可能需要强制转换:

(float)basicSalary ...

顺便说一句,许多变量,例如basicSalary,也应该是 类型float

作为最后的建议,除非您有特殊需要,否则通常建议默认使用double而不是到处使用。float

于 2013-02-15T18:06:25.720 回答
2

这是由整数除法引起的

monthlyTax = ((15/100) * (income/12));

在这里,15/100 的计算结果不是 0.15,而是 0(去掉了小数部分)。

更改公式以使用浮点值:

monthlyTax = ((15/100.f) * (income/12.f));

或者

monthlyTax = ((15/100.0) * (income/12.0));
于 2013-02-15T18:07:13.700 回答