package W1_wangjiashuo_202506050214; import java.util.Scanner; /** * 温度转换器程序 * 支持摄氏度(C)与华氏度(F)之间的相互转换 * 输入格式示例:36.6 C 或 97 F */ public class TemperatureConverter { /** * 将摄氏度转换为华氏度 * @param c 摄氏温度(浮点型) * @return 对应的华氏温度(浮点型) */ public static double celsiusToFahrenheit(double c) { return c * 9.0 / 5.0 + 32.0; } /** * 将华氏度转换为摄氏度 * @param f 华氏温度(浮点型) * @return 对应的摄氏温度(浮点型) */ public static double fahrenheitToCelsius(double f) { return (f - 32.0) * 5.0 / 9.0; } public static void main(String[] args) { // 支持命令行参数模式(加分项) if (args.length >= 1) { handleCommandLine(args); return; } // 控制台交互模式 Scanner scanner = new Scanner(System.in); System.out.print("请输入要转换的温度与单位(例如 36.6 C 或 97 F):"); String s = scanner.nextLine().trim(); scanner.close(); // 判空处理 if (s.isEmpty()) { System.out.println("输入为空,程序退出。"); return; } // 解析输入内容 String[] parts = s.split(" "); try { double value = Double.parseDouble(parts[0]); String unit = parts.length > 1 ? parts[1].toUpperCase() : "C"; convertAndPrint(value, unit); } catch (Exception e) { System.out.println("输入解析失败,请按示例输入数值与单位,例如:36.6 C"); } } /** * 处理命令行参数的温度转换 * @param args 命令行参数数组 */ private static void handleCommandLine(String[] args) { try { double value = Double.parseDouble(args[0]); String unit = args.length > 1 ? args[1].toUpperCase() : "C"; convertAndPrint(value, unit); } catch (Exception e) { System.out.println("命令行参数格式错误,示例:java TemperatureConverter 36.6 C"); } } /** * 执行温度转换并打印结果 * @param value 温度数值 * @param unit 温度单位(C/F) */ private static void convertAndPrint(double value, String unit) { 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。"); } } }