Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does division result in zero instead of a decimal?

Tags:

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.

like image 824
Chef Flambe Avatar asked Jan 18 '12 07:01

Chef Flambe


People also ask

Can a division result in 0?

The result depends on how division is implemented, and can either be zero, or sometimes the largest possible integer.

Why do we put zero after decimal?

Adding zero placeholders at the end of a decimal does not change the value of the decimal. Zero placeholders can be used to continue dividing to get a more accurate quotient.

How do you change an int to a decimal?

To implicitly convert an Int32 to a Decimal, firstly set a Int32 value. int val = 392; To convert Int32 to decimal, assign the value.


2 Answers

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))
like image 75
Mysticial Avatar answered Oct 04 '22 20:10

Mysticial


When you do 5/9, 5 and 9 are both integers and integer division happens. The result of integer division is an integer and it is the quotient of the two operands. So, the quotient in case of 5/9 is 0 and since you multiply by 0, tempC comes out to be 0. In order to not have integer division, atleast one of the two operands must be float.

E.g. if you use 5.0/9 or 5/9.0 or 5.0/9.0, it will work as expected.

like image 39
Divya Avatar answered Oct 04 '22 21:10

Divya