分部在飞 [英] Division on the fly

查看:148
本文介绍了分部在飞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Java编写一个小程序,将华氏温度转换为摄氏温度。它涉及扣除32并乘以5/9。所以我这样做了。

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);

但出于某种原因,5/9返回零会破坏这一切,甚至

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.

推荐答案

Java中默认为 int 。所以当你做 5/9 时,因为它们都是 int s,你会得到0.something,因为这是 int ,所以只存储0。解决方案:

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.

现在计算将在 double 方式,你会得到理想的结果。

Now the calculation will be in a double manner and you'll get the desired result.

这篇关于分部在飞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆