0

I'm working on week 2's problem set and I ran into a floating point exception. In trying to use printf to diagnose the problem, I'm finding something I can't figure out.

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

int main(void)
{
    int l = 65 / 14 * 100;
    float j = 65 / 14 * 100;
    printf("%i\n", l);   // prints 400
    printf("%f\n", j);   // prints 400.000000
}

I'd expect the output to be 464 for int, and 464.xxxx for float. Why are both of these rounding the answer down to 400? Every piece of documentation I find talks about how to round past x decimal places with c, but I can't find anything that explains the simple problem I'm having above.

How do I fix this so my computations output correctly?

1

It's not a floating point problem, it's an integer problem. ;-)

Look at this line:

    int l = 65 / 14 * 100;

It contains all integers. Additionally, consider the precedence of operations - what gets done in what order.

Since all the numbers are integers, this is going to do integer division. The precedence rules says that all this will be done left to right. So, 65/14 in integer division is 4. Multiply by 100, it's 400.

Now if the code looked like this, it would be floating point math:

int l = 65 / 14.0 * 100;

The result of this would be 464 and stored as an int.

The float result is the same logic. All the calculations are done with integers (no decimal point in sight.) So, the same result is generated, except that, at the end, it is cast from an int to a float and stored.

Try experimenting with different numbers as floats vs. decimals. Make the first number 65.0 and all the others integers and see if it changes things. Or, 100.0 as the float and the other two left as integers and see what happens! (This one will be the most interesting.)

Once you get it sorted out, here's another eye opener for you. Print out the float as it is now, and then print it out to about 30 decimal points and compare the output! ;-)

Kudos for experimenting and testing in order to understand!!!! ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Wow, perfect answer--definitely puts me on the right track to fixing the underlying problem. Coming from Javascript, I was baffled by what was happening since this is not a thing you even have to think about in that language. But the answer makes sense now that I understand it's doing integer math. Appreciate the thorough response!
    – Adam Mann
    Oct 22 '20 at 20:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .