1 changed files with 0 additions and 71 deletions
@ -1,71 +0,0 @@ |
|||
/****************************************************************************** |
|||
|
|||
Online Java Compiler. |
|||
Code, Compile, Run and Debug java program online. |
|||
Write your code in this editor and press "Run" button to execute it. |
|||
|
|||
*******************************************************************************/ |
|||
|
|||
import java.util.Scanner; |
|||
|
|||
/** |
|||
* TemperatureConverter.java |
|||
* |
|||
* 这是一个用于在摄氏度和华氏度之间转换的程序。 |
|||
* 程序包含两个静态方法,用于将摄氏温度转换为华氏温度,以及将华氏温度转换为摄氏温度。 |
|||
* main 方法支持用户输入温度值及单位(C 或 F),并输出转换结果。 |
|||
*/ |
|||
public class TemperatureConverter { |
|||
|
|||
/** |
|||
* 将摄氏度转换为华氏度 |
|||
* @param celsius 摄氏温度值 |
|||
* @return 转换后的华氏温度值 |
|||
*/ |
|||
public static double celsiusToFahrenheit(double celsius) { |
|||
// 华氏度 = 摄氏度 * 9/5 + 32
|
|||
return celsius * 9 / 5 + 32; |
|||
} |
|||
|
|||
/** |
|||
* 将华氏度转换为摄氏度 |
|||
* @param fahrenheit 华氏温度值 |
|||
* @return 转换后的摄氏温度值 |
|||
*/ |
|||
public static double fahrenheitToCelsius(double fahrenheit) { |
|||
// 摄氏度 = (华氏度 - 32) * 5/9
|
|||
return (fahrenheit - 32) * 5 / 9; |
|||
} |
|||
|
|||
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(); |
|||
scanner.close(); |
|||
|
|||
// 分离数字和单位
|
|||
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 result = celsiusToFahrenheit(value); |
|||
System.out.printf("%.2f C -> %.2f F\n", value, result); |
|||
} else if (unit.equals("F")) { |
|||
// 华氏度转换为摄氏度
|
|||
double result = fahrenheitToCelsius(value); |
|||
System.out.printf("%.2f F -> %.2f C\n", value, result); |
|||
} else { |
|||
System.out.println("未知的温度单位,请使用 C 或 F。"); |
|||
} |
|||
} catch (NumberFormatException e) { |
|||
System.out.println("无法解析温度值,请确保输入的是数字。"); |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue