2017-04-02 16 views
-1

代碼應該輸出華氏和攝氏表:如何創建華氏轉化爲攝氏在Java

public static void main(String[] args) { 
    System.out.println("Fahrenheit\tCelsius"); 
    System.out.println("======================="); 
    for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10) 
     { 
      System.out.printf("%5d  |", temp); 
      double sum = (temp + (9.0/5.0)) * 32; 
      System.out.printf("%5d", (int) sum); 
      System.out.println(); 
     } 
} 
+0

您的問題是否得到解決? –

+0

是的,我理解了它。謝謝! –

+0

怎麼樣接受一些答案? –

回答

0

如何創建華氏的轉換java中的攝氏溫度

恕我直言,最重要的一步是在考慮編碼之前瞭解問題。

Wikipedia是一個好的開始,搜索攝氏它給我們:

[℃] =([°F] - 32)×5/9

在Java那會是這樣的:

celsius = (fahrenheit -32.0) * 5.0/9.0; 

我認爲這是最好的做,在一個單獨的方法,這樣很容易對其進行測試:

public static double fahrenheitToCelsius(double fahrenheit) { 
    double celsius = (fahrenheit - 32.0) * 5.0/9.0; 
    return celsius; 
} 

注1:這是值得在測試前要在這個方法 - 2個顯著溫度:

  • 32°F == 0℃(冰的熔點)
  • 212°F = = 100℃(水的沸點)

所以只是做一些快速&髒象:

System.out.println("32 == " + fahrenheitToCelsius(32)); 
System.out.println("212 == " + fahrenheitToCelsius(212)); 

好得多,也許在這種簡單的情況下有點沉重,就是使用像JUnit這樣的框架。

注2:用於創建該表不爲張貼在問題,但只有一個printf採取具有在一個位置的格式一起的優點(調用上述方法之後明顯):

System.out.printf("%5.0f | %5.1f\n", fahrenheit, celsius); 

注3 :謹慎使用5/9 - 在Java中被解釋爲整數除法並且會導致零!

(上面的代碼僅僅是一個樣品,並沒有測試或調試

1

你需要做出兩個改變:

  • 刪除投到int(因爲它使價值失去精度)
  • printf中使用「.1f」(因爲您需要打印十進制數字a ND不是int)

下面應該工作:

System.out.printf("%10.1f", sum); 
+0

哇,很好!非常感謝你。更復雜一點,有沒有辦法讓整個輸出看起來好多了,Celsius的輸出看起來有點奇怪 –

+0

把'%.1f'改成'%10.1f',你會看到輸出對齊。我已經更新了答案。 –

0

一個更好的辦法是使用十進制格式類

import java.text.DecimalFormat; 

int numberToPrint = 10.234; 
DecimalFormat threePlaces = new DecimalFormat("##.#"); //formats to 1 decimal place 
System.out.println(threePlaces.format(numberToPrint)); 

應打印:

10.2 
0

如果你想讓輸出結果看起來像表格一樣,你必須使用java.util.Formatter

我改寫了你的片段,一點點:

public static void main(String[] args) { 
    Formatter formatter = new Formatter(System.out); 

    formatter.format("%-20s\n",  "---------------------------"); 
    formatter.format("%-10s %12s\n", "| Fahrenheit |", "Celsius |"); 
    formatter.format("%-20s\n",  "---------------------------"); 

    for (int farValue = -45; farValue <= 80; farValue += 5) { 
     double celValue = (farValue + (9.0/5.0)) * 32; 

     formatter.format("| %10d | %10.0f |\n", farValue, celValue); 
    } 
    formatter.format("%-20s\n", "---------------------------"); 
} 

輸出片斷長相酷似

--------------------------- 
| Fahrenheit | Celsius | 
--------------------------- 
|  -45 |  -1382 | 
|  -40 |  -1222 | 
... 
|  -30 |  -902 | 
---------------------------