2014-02-27 18 views
0

所以我目前正在研究一個非常簡單的程序。它所做的是將華氏度或攝氏度轉換爲開爾文,然後根據用戶的要求(f或c)將開氏值轉換並返回爲攝氏度或華氏度。Java - 開爾文到華氏轉換方法

我的攝氏溫度轉換似乎工作得很好,但華氏溫度是一個不同的故事。我們的教授說我們的輸出必須與給出的例子100%匹配,並且當我給出攝氏度值並請求攝氏度時,它總是返回我最初輸入的值。

但是,當轉換95攝氏度到華氏度時:203.28800000000007 我應該得到的價值是:203.0 此外,當我把50華氏度,並要求它返回華氏溫度,我得到這個:32.0。

我會發布包含我所有轉換方法的類,但任何人都可以幫我解決我可能會出錯的地方嗎?它看起來像我根據我的公式,它只是返回公式的部分加/減32.我試過公式的其他格式,但似乎沒有工作。

public class Temperature 

{ 

// Instance variable 

    private double degreesKelvin; // degrees in Kelvin 

// Constructor method: initialize degreesKelvin to zero 

    public Temperature() 
    { 
     degreesKelvin = 0; 
    } 

// Convert and save degreesCelius in the Kelvin scale 

    public void setCelsius(double degreesCelsius) 
    { 
     degreesKelvin = degreesCelsius + 273.16; 
    } 

// Convert degreesKelvin to Celsius and return the value 

    public double getCelsius() 
    { 
     double c = degreesKelvin - 273.16; 
     return c; 
    } 

// Convert and save degreesFahrenheit in the Kelvin scale 

    public void setFahrenheit(double degreesFahrenheit) 
    { 
     degreesKelvin = (5/9 * (degreesFahrenheit - 32) + 273); 
    } 

// Convert degreesKelvin to Fahrenheit and return the value 

    public double getFahrenheit() 
    { 
     double f = (((degreesKelvin - 273) * 9/5) + 32); 
     return f; 
    } 

} 

感謝您的幫助,我試圖尋找這個問題的解決辦法,但似乎沒有爲我工作至今。

+0

203.28800000000007可以縮放到返回203.2和您沒有方法把華氏和retur華氏溫度! – ItachiUchiha

+0

用5.0/9代替5/9和9.0/5代替9/5。 –

回答

2

當心整數除法,2點的整數(分割時)的結果產生一個整數:

5/9 = 0 
9/5 = 1 

爲了解決這個問題,投其中1到浮動類型,如:

5d/9 //or 5.0/9 

而且同樣與

9d/5 //or 9.0/5 
+0

啊,工作完美,謝謝!我的教授還沒有教過我們。其中一些數字仍然偏離我的一小部分,但我想我可能能夠將它們四捨五入。 – Alzecha

0

的問題發生,因爲同時存儲要添加2 73.16到攝氏度。額外的.16引入了這個錯誤。 爲95度celsiun

degreeKelvin = 273.16 + 95

現在在返回變得

5/9 *(273.16 + 95-273)32 == 5/9(95.16)32 == 203.2

5/9 *(273 + 95-273)+ 32 == 203

+0

不幸的是,根據轉換公式,.16是強制性的。儘管這種轉換的答案剛好是203.0,但我們給出的其他例子可能包含小數點後的許多數字。事實上,我沒有得到完全203.0只是發送一個信號,表明我的公式在某個地方是錯誤的。 – Alzecha