Browse Source

feat:添加w1文件夹及相关java代码

master
unknown 2 weeks ago
parent
commit
08341bca1b
  1. BIN
      w1/1b48557458c1a91e858d022367d257a5.png
  2. 1
      w1/README.md
  3. BIN
      w1/TemperatureConverter.class
  4. 70
      w1/TemperatureConverter.java

BIN
w1/1b48557458c1a91e858d022367d257a5.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

1
w1/README.md

@ -0,0 +1 @@
温度转换器程序 - 运行命令: java -cp w1 TemperatureConverter

BIN
w1/TemperatureConverter.class

Binary file not shown.

70
w1/TemperatureConverter.java

@ -0,0 +1,70 @@
import java.util.Scanner;
/**
* 温度转换器 - 支持摄氏度(C)与华氏度(F)之间互转
* 对应Python版本的温度转换程序
*/
public class TemperatureConverter {
/**
* 将摄氏度转换为华氏度
*
* @param c 摄氏温度值
* @return 对应的华氏温度值
*/
public static double celsiusToFahrenheit(double c) {
return c * 9.0 / 5.0 + 32.0;
}
/**
* 将华氏度转换为摄氏度
*
* @param f 华氏温度值
* @return 对应的摄氏温度值
*/
public static double fahrenheitToCelsius(double f) {
return (f - 32.0) * 5.0 / 9.0;
}
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("输入为空,程序退出。");
scanner.close();
return;
}
// 分割输入
String[] parts = input.split("\\s+");
try {
// 解析数值和单位
double value = Double.parseDouble(parts[0]);
String unit = (parts.length > 1) ? parts[1].toUpperCase() : "C";
if (unit.startsWith("C")) {
// 摄氏度 -> 华氏度
double f = celsiusToFahrenheit(value);
System.out.printf("%.2f °C = %.2f °F%n", value, f);
} else if (unit.startsWith("F")) {
// 华氏度 -> 摄氏度
double c = fahrenheitToCelsius(value);
System.out.printf("%.2f °F = %.2f °C%n", value, c);
} else {
System.out.println("未知单位,请使用 C 或 F。");
}
} catch (NumberFormatException e) {
System.out.println("输入解析失败,请按示例输入数值与单位,例如:36.6 C");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("输入格式错误,请确保包含数值和单位");
}
scanner.close();
}
}
Loading…
Cancel
Save