2 changed files with 46 additions and 0 deletions
@ -0,0 +1,2 @@ |
|||||
|
javac TemperatureConverter.java |
||||
|
java TemperatureConverter |
||||
@ -0,0 +1,44 @@ |
|||||
|
import java.util.Scanner; |
||||
|
|
||||
|
// 温度转换器:摄氏(C)与华氏(F)互转,复刻Python原程序逻辑
|
||||
|
public class TemperatureConverter { |
||||
|
// 摄氏转华氏
|
||||
|
public static double c2f(double c) { |
||||
|
return c * 9.0 / 5.0 + 32.0; |
||||
|
} |
||||
|
|
||||
|
// 华氏转摄氏
|
||||
|
public static double f2c(double f) { |
||||
|
return (f - 32.0) * 5.0 / 9.0; |
||||
|
} |
||||
|
|
||||
|
public static void main(String[] args) { |
||||
|
Scanner sc = new Scanner(System.in); |
||||
|
// 输入提示与Python完全一致
|
||||
|
System.out.print("请输入要转换的温度与单位(例如 36.6 C 或 97 F):"); |
||||
|
String input = sc.nextLine().strip(); |
||||
|
sc.close(); |
||||
|
|
||||
|
// 空输入处理
|
||||
|
if (input.isEmpty()) { |
||||
|
System.out.println("输入为空,程序退出。"); |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
// 解析输入并转换
|
||||
|
String[] parts = input.split(" "); |
||||
|
try { |
||||
|
double val = Double.parseDouble(parts[0]); |
||||
|
String unit = parts.length > 1 ? parts[1].toUpperCase() : "C"; |
||||
|
if (unit.startsWith("C")) { |
||||
|
System.out.printf("%.2f °C = %.2f °F\n", val, c2f(val)); |
||||
|
} else if (unit.startsWith("F")) { |
||||
|
System.out.printf("%.2f °F = %.2f °C\n", val, f2c(val)); |
||||
|
} else { |
||||
|
System.out.println("未知单位,请使用 C 或 F。"); |
||||
|
} |
||||
|
} catch (Exception e) { |
||||
|
System.out.println("输入解析失败,请按示例输入数值与单位,例如:36.6 C"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue