Emilia Clarke
Emilia Clarke

Reputation: 85

math operations with different types in C

I'm very new to C, and I'm trying to write a simple program that calculates the amount of taxes owed based on gross income and tax rate. I have no idea why owedTax prints as 0 with the following inputs.

#include <stdio.h>
int main()
{

// get user's AGI
double userAGI;
printf("enter agi:\n");
scanf("%lf",&userAGI)

// get tax rate
int taxRate;
printf("enter desired tax rate:\n");
scanf("%d",&taxRate);

// calculate owed tax
double owedTax = (taxRate / 100) * userAGI;
printf("%lf\n",owedTax);

return 0;
}

Ouput:

enter agi:
100
enter desired tax rate:
10
0.0000000

Why does owedTax print as 0?

Upvotes: 1

Views: 545

Answers (3)

iksemyonov
iksemyonov

Reputation: 4196

Fix

double owedTax = (taxRate / 100) * userAGI;

to

double owedTax = (taxRate / 100.0) * userAGI;
                            ^^^^^

or

double owedTax = ((double)taxRate / 100) * userAGI;
                  ^^^^^^^^

The problem is that in C and C++, when you divide two integers, an integer division is performed, that returns the integer part of the result, with the fractional part discarded.

Look:

10 / 100 = 0.1 in algebra. Discard the fractional part -> 0 remains.

If you want to divide two integers and get an exact floating-point result, explicitly cast one of the integers to a floating-point type. A common error indeed! (Done it myself many times.)

For the reference, I'm linking this excellent discussion here on SO:

What is the behavior of integer division in C?

Upvotes: 0

Change:

// calculate owed tax
double owedTax = (taxRate / 100.0) * userAGI;

You have to use 100.0 instead 100 to get the desired result.

If you divide two integers, an integer division is performed, discarding fractional part.

Upvotes: 0

Tom Karzes
Tom Karzes

Reputation: 24052

The problem is here:

double owedTax = (taxRate / 100) * userAGI;

Since taxRate is an integer, and 100 is an integer, it performs integer division, with the result being integer 0. It then converts this result to double and multiplies it by userAGI. To fix it, you just need to force it to do a floating divide, as follows:

double owedTax = (taxRate / 100.0) * userAGI;

Since 100.0 is a double constant, it will convert taxRate to double before performing the division.

Upvotes: 1

Related Questions