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

Python如何打印单个阶乘值 代码输出过多数值问题排查

问题原因排查

你目前贴出的代码逻辑本身是正确的,单独运行只会输出1次最终阶乘结果。出现多次多余输出的核心原因是*print语句缩进错误,被放入了while循环的内部代码块中*:

  • 错误缩进写法(每次循环都会执行打印,输出多个中间值)
while iCount <= iMax:
    iFactorial = iFactorial * iCount
    iCount = iCount + 1
    # 这里print被缩进,属于while循环内部代码,每次循环都会执行
    print("factorial of ", iMax, " is ", iFactorial)
  • 正确写法(print和while同级,循环全部执行完后仅打印1次最终结果,和你贴出的代码逻辑一致)
iMax = int(input("What is the number to factorialize: "))

iFactorial = 1
iCount = 1

while iCount <= iMax:
    iFactorial = iFactorial * iCount
    iCount = iCount + 1

# print没有缩进,和while同级,仅执行一次
print("factorial of ", iMax, " is ", iFactorial)

如果调整缩进后仍存在多余输出,检查代码其余位置是否有额外的print调用即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:06:02