cmathintegerdivisioninteger-division

Why does integer division result in zero instead of a decimal?


Teaching myself C and finding that when I do an equation for a temp conversion it won't work unless I change the fraction to a decimal. ie,

tempC=(.555*(tempF-32)) will work but tempC=((5/9)*(tempF-32)) won't work.

Why?
According to the book "C Primer Plus" it should work as I'm using floats for both tempC and tempF.


Solution

  • It looks like you have integer division in the second case:

    tempC=((5/9)*(tempF-32))
    

    The 5 / 9 will get truncated to zero.

    To fix that, you need to make one of them a floating-point type:

    tempC=((5./9.)*(tempF-32))