commit
3cbfe9ec4d
3 changed files with 90 additions and 0 deletions
@ -0,0 +1,57 @@ |
|||
# 温度转换器示例程序(Python) |
|||
# 支持摄氏度(C)与华氏度(F)之间互转 |
|||
|
|||
def celsius_to_fahrenheit(c): |
|||
"""将摄氏度转换为华氏度。 |
|||
|
|||
参数: |
|||
c (float): 摄氏温度 |
|||
|
|||
返回: |
|||
float: 对应的华氏温度 |
|||
""" |
|||
return c * 9.0 / 5.0 + 32.0 |
|||
|
|||
|
|||
def fahrenheit_to_celsius(f): |
|||
"""将华氏度转换为摄氏度。 |
|||
|
|||
参数: |
|||
f (float): 华氏温度 |
|||
|
|||
返回: |
|||
float: 对应的摄氏温度 |
|||
""" |
|||
return (f - 32.0) * 5.0 / 9.0 |
|||
|
|||
|
|||
def main(): |
|||
# 提示用户输入,格式示例:"36.6 C" 或 "97 F" |
|||
s = input('请输入要转换的温度与单位(例如 36.6 C 或 97 F):').strip() |
|||
if not s: |
|||
print('输入为空,程序退出。') |
|||
return |
|||
|
|||
parts = s.split() |
|||
try: |
|||
# 允许用户输入两个部分:数值与单位 |
|||
value = float(parts[0]) |
|||
unit = parts[1].upper() if len(parts) > 1 else 'C' |
|||
except Exception as e: |
|||
print('输入解析失败,请按示例输入数值与单位,例如:36.6 C') |
|||
return |
|||
|
|||
if unit.startswith('C'): |
|||
# 从摄氏度转换为华氏度 |
|||
f = celsius_to_fahrenheit(value) |
|||
print(f"{value} °C = {f:.2f} °F") |
|||
elif unit.startswith('F'): |
|||
# 从华氏度转换为摄氏度 |
|||
c = fahrenheit_to_celsius(value) |
|||
print(f"{value} °F = {c:.2f} °C") |
|||
else: |
|||
print('未知单位,请使用 C 或 F。') |
|||
|
|||
|
|||
if __name__ == '__main__': |
|||
main() |
|||
@ -0,0 +1,5 @@ |
|||
public class Helloworld { |
|||
public static void main(String[]args){ |
|||
System.out.println("Hello world!"); |
|||
} |
|||
} |
|||
@ -0,0 +1,28 @@ |
|||
import java.util.Scanner;//使用Scanner类获取输入
|
|||
public class TemperatureConverter { |
|||
public static double celsius_to_fahrenheit(double c){ |
|||
return c*9.0/5.0+32.0; |
|||
} |
|||
//函数将摄氏度转换为华氏度。
|
|||
public static double fahrenheit_to_celsius(double f){ |
|||
return (f - 32.0) * 5.0 / 9.0; |
|||
} |
|||
//函数将华氏度转换为摄氏度。
|
|||
public static void main(String[]args){ |
|||
Scanner scan=new Scanner(System.in);//创建scan对象
|
|||
System.out.println("请输入要转换的温度和单位:(例如 36.6 C 或 97 F)"); |
|||
double temp=scan.nextDouble(); //输入双精度浮点数数值
|
|||
char unit=scan.next().charAt(0); //输入浮点数后面的字符C或F(温度或华氏度)
|
|||
if(unit =='C'){ |
|||
double f=celsius_to_fahrenheit(temp); |
|||
System.out.printf("%.1f ℃=%.2f ℉\n",temp,f); |
|||
} |
|||
//判断温度并输出华氏度
|
|||
if(unit =='F'){ |
|||
double c=fahrenheit_to_celsius(temp); |
|||
System.out.printf("%.1f ℉=%.2f ℃\n",temp,c); |
|||
} |
|||
//判断华氏度并输出温度
|
|||
scan.close(); |
|||
} |
|||
} |
|||
Loading…
Reference in new issue