2012-12-19 93 views
0

我必須將攝氏溫度轉換爲華氏溫度。但是,當我以攝氏度打印溫度時,我得到了錯誤的答案!請幫忙 ! (公式是c =(5/9)*(f -32)。當我輸入1度數時,我得到c = -0.0。我不知道什麼是錯的:s溫度轉換

這裏是代碼

import java.io.*; // import/output class 
public class FtoC { // Calculates the temperature in Celcius 
    public static void main (String[]args) //The main class 
    { 
    InputStreamReader isr = new InputStreamReader(System.in); // Gets user input 
    BufferedReader br = new BufferedReader(isr); // manipulates user input 
    String input = ""; // Holds the user input 
    double f = 0; // Holds the degrees in Fahrenheit 
    double c = 0; // Holds the degrees in Celcius 
    System.out.println("This program will convert the temperature from degrees Celcius to Fahrenheit."); 
    System.out.println("Please enter the temperature in Fahrenheit: "); 
    try { 
     input = br.readLine(); // Gets the users input 
     f = Double.parseDouble(input); // Converts input to a number 
    } 
    catch (IOException ex) 
    { 
     ex.printStackTrace(); 
    } 
    c = ((f-32) * (5/9));// Calculates the degrees in Celcius 
    System.out.println(c); 
    } 
} 
+0

非常感謝你:)我很困惑哈哈:p – MadcapClover

回答

4

你正在做的整數除法,因此5/9會給你0

將其更改爲浮點除法: - 。

c = ((f-32) * (5.0/9)); 

或,執行乘法第一(從分割刪除括號): -

c = (f-32) * 5/9; 

由於,f加倍。分子只會是double。我認爲這種方式更好。

0

您應該嘗試使用double而不是int,因爲這會導致精度損失。而不是使用整個公式,使用一個計算在一個時間

實施例:使用合適的鑄造 雙此= 5/9

的F - 雙32

0

使用這種相當:

c = (int) ((f-32) * (5.0/9));// Calculates the degrees in Celcius 

,因爲它涉及的部門,你不應該只使用整數得到適當的分工

0

使用此

System.out.println((5F/9F) * (f - 32F)); 
0

除非明確指定,否則Java會將所有數字視爲整數。由於整數不能存儲數字的小數部分,所以當執行整數除法時,其餘部分將被丟棄。因此:5/9 == 0

Rohit的解決方案c = (f-32) * 5/9;可能是最乾淨的(儘管缺乏顯式類型可能會導致一些混淆)。