You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用for、while循环实现华氏度转摄氏度转换表的程序编写需求

华氏度转摄氏度转换表实现(Python版)

转换公式:摄氏度 = (华氏度 - 32) * 5 / 9

1. while 循环实现

实现逻辑:先读取用户输入的三个参数,校验步长合法性后,从起始华氏度开始循环,每次判断当前华氏度是否未超过结束值,满足条件则输出转换结果,再累加步长进入下一轮循环。

# 读取用户输入
start_f = float(input("请输入华氏度起始值:"))
end_f = float(input("请输入华氏度结束值:"))
step = float(input("请输入步长增量:"))

# 步长合法性校验
if step == 0:
    print("步长不能为0")
    exit()
# 适配步长为负的场景(支持从高到低输出转换表)
if step > 0:
    condition = lambda current: current <= end_f
else:
    condition = lambda current: current >= end_f

current_f = start_f
print("华氏度\t摄氏度")
print("----------------")
while condition(current_f):
    c = (current_f - 32) * 5 / 9
    print(f"{current_f:.1f}\t{c:.2f}")
    current_f += step

2. for 循环实现

实现逻辑:通过自定义生成器生成符合范围要求的华氏度序列,循环遍历每个值输出转换结果,循环终止由序列的结束边界自动判断,无需设置固定循环次数。

# 读取用户输入
start_f = float(input("请输入华氏度起始值:"))
end_f = float(input("请输入华氏度结束值:"))
step = float(input("请输入步长增量:"))

# 步长合法性校验
if step == 0:
    print("步长不能为0")
    exit()

print("华氏度\t摄氏度")
print("----------------")
# 自定义生成器适配整数、浮点数和正负步长场景
def f_generator(start, end, step):
    current = start
    if step > 0:
        while current <= end:
            yield current
            current += step
    else:
        while current >= end:
            yield current
            current += step

for current_f in f_generator(start_f, end_f, step):
    c = (current_f - 32) * 5 / 9
    print(f"{current_f:.1f}\t{c:.2f}")

运行示例

输入参数:

  • 起始值:32
  • 结束值:100
  • 步长:10
    输出结果:
华氏度	摄氏度
----------------
32.0	0.00
42.0	5.56
52.0	11.11
62.0	16.67
72.0	22.22
82.0	27.78
92.0	33.33
100.0	37.78

内容的提问来源于stack exchange,提问作者Chintan Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:24:03