/** * 温度转换工具类 * 实现摄氏度与华氏度的双向转换,并提供测试用例 * @author [你的姓名] * @version 1.0 */ public class TemperatureConverter { /** * 摄氏度转华氏度 * 公式: F = C × 9/5 + 32 * @param celsius 摄氏温度值 * @return 对应的华氏温度值 */ public static double celsiusToFahrenheit(double celsius) { return celsius * 9.0 / 5.0 + 32.0; } /** * 华氏度转摄氏度 * 公式: C = (F - 32) × 5/9 * @param fahrenheit 华氏温度值 * @return 对应的摄氏温度值 */ public static double fahrenheitToCelsius(double fahrenheit) { return (fahrenheit - 32.0) * 5.0 / 9.0; } /** * 主方法:程序入口,包含测试用例 * @param args 命令行参数(可选,支持直接传入温度值和单位进行转换) */ public static void main(String[] args) { // 示例测试用例 double testC = 25.0; double testF = 77.0; System.out.println("=== 温度转换测试 ==="); System.out.printf("%.1f ℃ 转换为华氏度: %.1f ℉%n", testC, celsiusToFahrenheit(testC)); System.out.printf("%.1f ℉ 转换为摄氏度: %.1f ℃%n", testF, fahrenheitToCelsius(testF)); // 支持命令行参数模式(加分项) if (args.length == 2) { try { double temp = Double.parseDouble(args[0]); String unit = args[1].toUpperCase(); if (unit.equals("C")) { System.out.printf("命令行转换: %.1f ℃ = %.1f ℉%n", temp, celsiusToFahrenheit(temp)); } else if (unit.equals("F")) { System.out.printf("命令行转换: %.1f ℉ = %.1f ℃%n", temp, fahrenheitToCelsius(temp)); } else { System.out.println("单位错误,请使用 C 或 F"); } } catch (NumberFormatException e) { System.out.println("温度值格式错误,请输入数字"); } } } }