import java.util.Scanner; public class TemperatureConverter { // 将摄氏度转换为华氏度 public static double celsiusToFahrenheit(double c) { return c * 9.0 / 5.0 + 32.0; } // 将华氏度转换为摄氏度 public static double fahrenheitToCelsius(double f) { return (f - 32.0) * 5.0 / 9.0; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("请输入要转换的温度与单位(例如 36.6 C 或 97 F):"); String input = scanner.nextLine().trim(); if (input.isEmpty()) { System.out.println("输入为空,程序退出。"); scanner.close(); return; } String[] parts = input.split(" "); double value; String unit; try { value = Double.parseDouble(parts[0]); if (parts.length > 1) { unit = parts[1].toUpperCase(); } else { unit = "C"; } } catch (Exception e) { System.out.println("输入解析失败,请按示例输入数值与单位,例如:36.6 C"); scanner.close(); return; } if (unit.startsWith("C")) { double f = celsiusToFahrenheit(value); System.out.printf("%.2f °C = %.2f °F%n", value, f); } else if (unit.startsWith("F")) { double c = fahrenheitToCelsius(value); System.out.printf("%.2f °F = %.2f °C%n", value, c); } else { System.out.println("未知单位,请使用 C 或 F。"); } scanner.close(); } }