Reputation: 553
I have a very small question that some of you might even think that the question doesn't worth wasting stackoverflow servers resources. I have a formula that calculates fahrenheit of given santigrant. C is the value is read from keyboad. For C = 1, the num must be 33.8 but it outputs as 33.0 because java thinks 9 / 8 as 1.0, not 1.8. I'm really stuck with that. I can use 1.8 * C + 32 but I just want to know if there is another solution.
double num = (9 / 5) * C + 32; // Calculates as 1 * C + 32 which is wrong;
double num = (9.0 / 5.0) * C + 32; // Calculates as 1.8 * C + 32 which is true;
Upvotes: 1
Views: 2411
Reputation: 718678
It depends whether C is integer or floating point.
If C is floating point, then there is no significantly different solution to the one that you have found. (Obviously there are minor differences in the syntax and stuff like that. But they just amount to cosmetic changes to the correct solution.)
If C is integer, then the alternative is to use a lookup table. (But that's not a good alternative, unless you are running on crippled hardware that doesn't have native floating point arithmetic instructions.)
The real problem here is that that you have told Java to do part of the calculation using integer division ... by using integer literals at key points in the expression. Integer division in Java produces and integer result, but you really need a (mathematical) real value at that point. Java is simply doing what you have told it to do.
In short, Java is NOT getting it wrong. You are ... by telling Java to do the calculation the wrong way.
Upvotes: 1
Reputation: 47699
You need to understand the difference between integers and floating-point numbers.
double
and float
declare floating-point numbers, while long
and int
(and char
and byte
and short
) declare integers. When you do arithmetic with only integers you get an integer result.
"Literals" like 7
and 589
are considered integers unless they contain a decimal point (eg, 7.0
or 0.589
or 123.456
). If they contain that decimal point they are considered floating point.
So, if you have an expression (like 9 / 5
) that is all literals, and you want the floating-point result, make at least one of the literals contain a decimal point (eg, 9.0 / 5
). And it's good practice to always tack on the .0
when coding literals in floating-point expressions.
Upvotes: 0
Reputation: 1356
It is because it is treating both the 9 and 5 as integers. You have answered your own question with the line below. That is the shortest and best way to do what you wish.
Upvotes: 1
Reputation: 162761
The way to express literal doubles in java is to suffix with a d
. Like this:
double num = (9d / 5d) * C + 32d;
Literal floats are similar. Just use an f
suffix. Like this:
float num = (9f / 5f) * C + 32f;
Upvotes: 4