问题
I'm trying to make a small program in Java which converts Fahrenheit to Celsius. It involves deducting 32 and multiplying by 5/9. So I did this.
double Fahrenheit = 100;
double celsius = (Fahrenheit - 32) * (5/9);
System.out.println(celsius);
But for some reason that 5/9 returns zero which ruins it all, even
double s = 5/9;
returns zero and I don't know why. The only way I found I can do it is if I declare everything and do it slowly, step by step.
double x = 5, p = 9, n = (x/p), Fah = 100;
double Cel = Fah - 32;
Cel = Cel*n;
Can anyone tell me why this sort of thing happens, I thought at least declaring it as a double would return a value. And if anyone knows, a way round it.
回答1:
Numbers are int
by default in Java. So when you do 5/9
, since they're both int
s, you'll get 0.something, and since this is an int
, only 0 will be stored. Solution:
double s = 5.0/9; //or 5d/9
Note that you can only explicitly cast one side, the other will be implicitly cast.
Now the calculation will be in a double
manner and you'll get the desired result.
回答2:
or you can do (5d/9d); // OR (5d/9)
making 5
and 9
explicit double
回答3:
It's good practice, when you deal with doubles, to write code like this:
double Fahrenheit = 100.0;
double celsius = (Fahrenheit - 32.0) * (5.0 / 9.0);
来源:https://stackoverflow.com/questions/21400191/division-on-the-fly