2

I am doing a CS50 problem-Half. I did the problem and it kinda worked, but when entering for example:

Bill before tax and tip: 12.50
Sale Tax Percent: 8.875
Tip percent: 20

It outputs $7.80 and not $8.17.

When entering:

Bill before tax and tip: 100
Sale Tax Percent: 20
Tip percent: 10

It works.

Why is that when giving decimals its wrong and when giving round numbers it works?

#include <cs50.h>
#include <stdio.h>

float half(float bill, float tax, int tip);

int main(void)
{
    float bill_amount = get_float("Bill before tax and tip: ");
    float tax_percent = get_float("Sale Tax Percent: ");
    int tip_percent = get_int("Tip percent: ");

    printf("You will owe $%.2f each!\n", half(bill_amount, tax_percent, tip_percent));
}

// TODO: Complete the function
float half(float bill, float tax, int tip)
{
    float price;
    tax = bill * tax / 100.0;
    tip = (bill + tax) * tip / 100;
    price = bill + tax + tip;
    return price / 2;
}

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
Savana01
  • 23
  • 2
  • `tip`, being an `int`, is getting truncated in your floating point calculations. – Paul Lynch May 09 '23 at 11:42
  • How can an `int` get _truncated_? – Armali May 09 '23 at 11:46
  • 2
    @Armali My bad, the floating point result is truncated when stored back into `tip`. – Paul Lynch May 09 '23 at 11:58
  • 2
    It's rarely a good idea to overwrite the input parameters to a function, as you are doing to the `tax` and `tip` parameters in the `half()` function. Instead, declare local working variables: `float tax_amount;` and `float tip_amount;` and calculate/use those. – jarmod May 09 '23 at 12:04
  • 1
    @Savana01, 1) Save time, enable all warnings. 2) Avoid mixing `float` and `double` math. Use one. 3) Consider whole number of cents, rather than money as dollars. – chux - Reinstate Monica May 09 '23 at 12:05

1 Answers1

2

With the input

Bill before tax and tip: 12.50
Sale Tax Percent: 8.875
Tip percent: 20

the line

tax = bill * tax / 100.0;

will evaluate to

tax = 12.50 * 8.875 / 100.0;

which is equivalent to:

tax = 1.109375;

The line

tip = (bill + tax) * tip / 100;

is therefore equivalent to

tip = (12.50 + 1.109375) * 20 / 100;

which is equivalent to:

tip = 2.721875;

However, the problem is that the variable tip is of type int, which is only able to represent whole numbers. Therefore, you will be assigning the value 2 instead of 2.721875 to tip.

To fix this, I suggest that you create a new variable that is of type float and use that variable for storing the value.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39