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.
54 lines
1.9 KiB
54 lines
1.9 KiB
import java.util.Scanner;
|
|
/**
|
|
* 温度转换器
|
|
* 功能:支持摄氏度(C)与华氏度(F)之间的相互转换
|
|
*/
|
|
public class TemperatureConverter {
|
|
/**
|
|
* 摄氏度转换为华氏度
|
|
* @param celsius 摄氏温度值
|
|
* @return 华氏温度值
|
|
*/
|
|
public static double celsiusToFahrenheit(double celsius) {
|
|
return celsius * 9.0 / 5.0 + 32.0;
|
|
}
|
|
/**
|
|
* 华氏度转换为摄氏度
|
|
* @param fahrenheit 华氏温度值
|
|
* @return 摄氏温度值
|
|
*/
|
|
public static double fahrenheitToCelsius(double fahrenheit) {
|
|
return (fahrenheit - 32.0) * 5.0 / 9.0;
|
|
}
|
|
public static void main(String[] args) {
|
|
Scanner scanner = new Scanner(System.in);
|
|
System.out.println("===== 温度转换器 =====");
|
|
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(" ");
|
|
try {
|
|
double value = Double.parseDouble(parts[0]);
|
|
String unit = "C";
|
|
if (parts.length >= 2) {
|
|
unit = parts[1].toUpperCase();
|
|
}
|
|
if (unit.startsWith("C")) {
|
|
double f = celsiusToFahrenheit(value);
|
|
System.out.printf("%.1f °C = %.2f °F%n", value, f);
|
|
} else if (unit.startsWith("F")) {
|
|
double c = fahrenheitToCelsius(value);
|
|
System.out.printf("%.1f °F = %.2f °C%n", value, c);
|
|
} else {
|
|
System.out.println("未知单位,请使用 C 或 F。");
|
|
}
|
|
} catch (Exception e) {
|
|
System.out.println("输入解析失败,请按示例输入:36.6 C");
|
|
}
|
|
scanner.close();
|
|
}
|
|
}
|