You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1.9 KiB

import java.util.Scanner;

/**

  • 温度转换程序(与Python版本功能完全等效)

  • 输入格式:温度值 + 空格 + 单位(C/F),例如 36.6 C 或 97 F

  • 功能:实现摄氏温度↔华氏温度的相互转换 */ public class TemperatureConverter { // 摄氏温度转换为华氏温度的核心方法 public static double celsiusToFahrenheit(double celsius) { return celsius * 9.0 / 5.0 + 32; }

    // 华氏温度转换为摄氏温度的核心方法 public static double fahrenheitToCelsius(double fahrenheit) { return (fahrenheit - 32) * 5.0 / 9.0; }

    // 程序主入口,处理输入和输出逻辑 public static void main(String[] args) { // 创建Scanner对象接收用户输入 Scanner scanner = new Scanner(System.in);

     // 提示语与你的Python程序完全一致
     System.out.print("请输入要转换的温度与单位(例如 36.6 C 或 97 F):");
    
     // 读取温度值和单位(兼容空格分隔的输入格式)
     double temperature;
     String unit;
     try {
         temperature = scanner.nextDouble(); // 读取温度数值
         unit = scanner.next().toUpperCase(); // 读取单位并统一转为大写(兼容小写输入)
     } catch (Exception e) {
         System.out.println("输入格式错误!请按示例格式输入(如:36.6 C)");
         scanner.close();
         return;
     }
    
     // 根据单位执行转换并输出结果
     if (unit.equals("C")) {
         double result = celsiusToFahrenheit(temperature);
         System.out.printf("%.2f C = %.2f F%n", temperature, result);
     } else if (unit.equals("F")) {
         double result = fahrenheitToCelsius(temperature);
         System.out.printf("%.2f F = %.2f C%n", temperature, result);
     } else {
         System.out.println("单位错误!仅支持 C(摄氏)或 F(华氏)");
     }
    
     // 关闭Scanner,释放资源
     scanner.close();
    

    } }