初學 Java 寫攝氏度轉華氏度(`f = c * 9/5 + 32`)時,常遇到兩個問題:結果精度丟失(整數除法) 和 小數位數不固定。本文通過經典案例拆解成因並給出標準解法。
Scanner in = new Scanner(System.in);
int c = in.nextInt();
double f = c * 9 / 5 + 32; // 錯誤:整數運算
System.out.println(f); // 輸入 37 → 輸出 98.0 (預期 98.6)
**現象**:無論輸入多少,結果小數部分總是 `.0`。
Java 中 `int` 與 `int` 運算結果仍為 `int`。表達式 `c * 9 / 5` 從左到右計算:
只要參與運算的任一操作數是浮點類型,整個表達式提升為浮點運算。最簡單方式:乘以 `1.0` 或將 `9` 改為 `9.0`。
double f = c * 9.0 / 5 + 32; // 或 c * 1.0 * 9 / 5 + 32
// 輸入 37 → 98.6
使用 `java.text.DecimalFormat` 或 `String.format` / `printf` 控制輸出格式。
double f = c * 9.0 / 5 + 32;
DecimalFormat df = new DecimalFormat("#.00"); // 0 強制顯示,# 不顯示前導/尾隨零
System.out.println(df.format(f)); // 98.60
System.out.printf("華氏度: %.2f°F%n", f); // 98.60°F
// 或
String formatted = String.format("%.2f", f);
import java.util.Scanner;
import java.text.DecimalFormat;
public class TempConvert {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("請輸入攝氏度: ");
int c = in.nextInt();
// 1. 浮點運算保證精度
double f = c * 9.0 / 5 + 32;
// 2. 格式化輸出
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("華氏度: " + df.format(f) + "°F");
// 也可直接 printf
System.out.printf("華氏度: %.2f°F%n", f);
}
}
掌握這兩點,溫度轉換與各類數值計算將不再出現「少位小數」的尷尬。