Browse Source

上传文件至 'W1'

main
GaoGeng 4 weeks ago
parent
commit
27013b7ee6
  1. BIN
      W1/AI协助记录.docx
  2. 12
      W1/README.md
  3. 69
      W1/TemperatureConverter.java
  4. BIN
      W1/运行结果.png

BIN
W1/AI协助记录.docx

Binary file not shown.

12
W1/README.md

@ -0,0 +1,12 @@
# 🌡️ 温度转换器 (Temperature Converter)
一个简单的 Java 命令行工具,支持摄氏度 (°C) 与华氏度 (°F) 的双向转换。
## 🚀 编译与运行
请确保已安装 **JDK**,并在终端(CMD/Terminal)中进入代码所在目录执行以下命令:
### 1. 编译代码
`.java` 源文件编译为 `.class` 字节码文件:
```bash
javac TemperatureConverter.java

69
W1/TemperatureConverter.java

@ -0,0 +1,69 @@
import java.util.Scanner;
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);
// 提示用户输入,格式示例:"36.6 C" 或 "97 F"
System.out.print("请输入要转换的温度与单位(例如 36.6 C 或 97 F):");
// 读取整行输入并去除首尾空格
String s = scanner.nextLine().trim();
if (s.isEmpty()) {
System.out.println("输入为空,程序退出。");
scanner.close();
return;
}
String[] parts = s.split("\\s+"); // 使用正则表达式分割空白字符,类似 Python 的 split()
double value;
String unit;
try {
// 允许用户输入两个部分:数值与单位
value = Double.parseDouble(parts[0]);
// 如果第二部分存在则转为大写,否则默认为 'C'
unit = (parts.length > 1) ? parts[1].toUpperCase() : "C";
} catch (Exception e) {
System.out.println("输入解析失败,请按示例输入数值与单位,例如:36.6 C");
scanner.close();
return;
}
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。");
}
scanner.close();
}
}

BIN
W1/运行结果.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

Loading…
Cancel
Save