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.

45 lines
1.5 KiB

import java.util.Scanner;
// 温度转换:摄氏(C) ↔ 华氏(F)
public class TemperatureConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入带有符号的温度值: ");
String input = scanner.nextLine();
scanner.close();
// 空输入直接报错
if (input.length() < 2) {
System.out.println("输入格式错误");
return;
}
// 取最后一位为单位,前面为数值字符串
char unit = input.charAt(input.length() - 1);
String numStr = input.substring(0, input.length() - 1);
try {
double num = Double.parseDouble(numStr);
double result;
char resUnit;
if (unit == 'C' || unit == 'c') {
// 摄氏 → 华氏
result = 1.8 * num + 32;
resUnit = 'F';
} else if (unit == 'F' || unit == 'f') {
// 华氏 → 摄氏
result = (num - 32) / 1.8;
resUnit = 'C';
} else {
System.out.println("输入格式错误");
return;
}
// 输出保留两位小数
System.out.printf("转换后的温度是%.2f%c%n", result, resUnit);
} catch (NumberFormatException e) {
System.out.println("输入格式错误");
}
}
}