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.
 
 
 

71 lines
2.3 KiB

import java.util.Scanner;
/**
* 温度转换程序
* 实现摄氏温度与华氏温度之间的相互转换
* @author 你的名字
*/
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) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入温度和单位(例如:36.6 C 或 97 F):");
String input = scanner.nextLine().trim();
if (input.isEmpty()) {
System.out.println("输入不能为空,请重新输入。");
return;
}
// 解析输入的数值和单位
String[] parts = input.split("\\s+");
if (parts.length < 2) {
System.out.println("输入格式不正确,请输入如 '36.6 C' 的格式。");
return;
}
try {
double value = Double.parseDouble(parts[0]);
String unit = parts[1].toUpperCase();
if (unit.equals("C")) {
double fahrenheit = celsiusToFahrenheit(value);
System.out.printf("%.1f°C 转换为华氏度是: %.1f°F%n", value, fahrenheit);
} else if (unit.equals("F")) {
double celsius = fahrenheitToCelsius(value);
System.out.printf("%.1f°F 转换为摄氏度是: %.1f°C%n", value, celsius);
} else {
System.out.println("不支持的单位,请使用 C 或 F。");
}
} catch (NumberFormatException e) {
System.out.println("温度数值格式不正确,请输入有效的数字。");
} finally {
scanner.close();
}
}
}