0
\$\begingroup\$

I have a question that may be easily answered, but the answer evades me. In regards to numeric operations, how come when I code this:

double celsius = 30;
double fahrenheit = (celsius + 32.0) / (5/9);

I get an answer:

fahrenheit = infinity;

But, when I code this:

double fahrenheit = (celsius + 32.0) / (5.0/9);  // with a decimal place after 5 or 9

The answer comes out correctly as 111.6?

Shouldn't the (5/9) automatically become a double without the decimal, or am I incorrect?

\$\endgroup\$
1
  • \$\begingroup\$ This site is for reviewing working code to make it better. If you don't understand why your code does what it does, you should try to debug it (hint: what is the result of 5/9?) or ask on Stack Overflow. \$\endgroup\$
    – svick
    Commented Jul 23, 2013 at 11:06

2 Answers 2

2
\$\begingroup\$

Division by zero gets you infinity.

Note that (5/9) is an int expression, and resolves to int 0!

To fix things, make your literals doubles :

double celsius = 30d;
double fahrenheit = (celsius + 32.0d) / (5d/9d);
\$\endgroup\$
1
\$\begingroup\$
Shouldn't the (5/9) automatically become a double without the decimal, or am I incorrect?

I think you want an answer to Doesn't instead of shouldn't. No it doesn't become that.

Simply stated int divided by an int can only give an int. So 5/9 becomes 0 point something which needs to be truncated to make it an integer. Hence 0.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.