-2
#include <stdio.h>

int main()
{
    float income;
    printf("enter your annual income here:");
    scanf("%f", &income);
    if (income < 250000)
    {
        printf("no income tax"); /* code */
    }
    else if (income >= 250000 && income < 500000)
    {
        printf("your income tax will be:%f", 5 / 100 * income);
    }
    else if (income >= 500000 && income < 1000000)
    {
        printf("your income tax will be:%f", 20 / 100 * income);
    }
    else if (income >= 1000000)
    {
        printf("your income tax will be:%f", 30 / 100 * income);
    }

    return 0;
}

When I run the code, entering values more than 250000, I still get 0 as my tax output, even though I have used the float data type.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

1

In the expression 5 / 100 * income, the multiplication operator * and division operator / have equal precedence and group from left to right. So it parses as (5 / 100) * income

The subexpression 5 / 100 has integer arguments to the division operator, so the result is truncated to an integer. This results in 0.

If you change either operand (or both) to a floating point constant, i.e. 5.0 / 100, 5 / 100.0, or 5.0 / 100.0, then floating point division will occur and you'll get the expected result.

20 / 100 and 30 / 100 have the same problem, so change those to 20.0 / 100 and 30.0 / 100 respectively.

Or get rid of the division entirely and use the constants 0.05, 0.2, and 0.3.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 2
    Strictly, using `5.0 / 100` will produce a `double` result (as `5.0` is a `double` constant). You could use `5.0f / 100` to produce a `float`, or you can decide not to fuss about it as the argument to `printf()` will be converted to a `double` anyway because of the ellipsis in the variadic template for `printf()`. – Jonathan Leffler Sep 08 '21 at 20:05
  • Suggestion: refer to [operator precedence](https://en.cppreference.com/w/c/language/operator_precedence) and [implicit conversions](https://en.cppreference.com/w/c/language/conversion). It's essential to the problem that the expression is evaluated from left to right, and that the conversion to a floating point type doesn't happen until it's too late. – Yun Sep 08 '21 at 20:06