Division on the fly [duplicate]

最后都变了- 提交于 2019-12-02 08:54:31

问题


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 ints, 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!