C中的算术不评估

时间:2013-02-15 18:03:51

标签: c

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

如果我将basicSalary提供为50000而将所有其他输入值提供为0,那么monthTax数字应为零,当它应该在4000左右时。

有人可以解释一下为什么会这样吗?

#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;
}

2 个答案:

答案 0 :(得分:6)

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

原作者可能意味着浮点除15.0 / 100.0

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

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

(float)basicSalary ...

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

作为最后一条建议,默认情况下,除非您有特殊需要,否则通常建议在任何地方使用double代替float

答案 1 :(得分: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));
相关问题