开发者

Successfully parsed a String into a Double, but all subsequent calculations fail

I'm writing a program for my Java class and we were asked to design a program, using GUI, that accepts a temperature value and converts to others, such as from Fahrenheit to Celsius and Kelvin. I've run into a problem though:

if (event.getSource() == fahrText)  
                {  
                string = event.getActionCommand();  
                tempF = Double.parseDouble(string);  
                tempC = (tempF - 32) * (5/9);  
                tempK = tempC + 273.15;  
  开发者_如何学Python              resultF.setText("Fahr: " + tempF);  
                resultC.setText("Cels: " + tempC);  
                resultK.setText("Kelv: " + tempK);  
            }  

No matter what number I enter into the "fahrText" JTextField I get Celsius as 0, while tempF shows the value I entered. Any suggestions as to why? I used Double.valueOf(string) with the same results.


Try 5.0/9.0 - 5/9 is integer division, and equal to 0. An integer division gives you an integer - regardless of which type you happen to assign the result to.

You could also keep a private final static double FToCFactor = 5.0/9.0; around and multiply with that.


The expression

5/9

represents an integer division. The result of that expression is 0.

What you want is a floating point division. It can be achieved with

5.0/9.0


Use double constants (e.g., 32.0d) instead of integers for all of your math. You're ending up doing integer math instead of floating point math.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜