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

Python WAP代码问题:输入多位数求各位阶乘,输出对应数字不符

问题:多位数各位数字阶乘计算错误(输出累加值而非单个数字的阶乘)

编写Python代码实现输入多位数并计算各位数字的阶乘时,出现异常:阶乘计算结果正确,但输出的对应数字不符合预期。预期应输出各位数字1、2、3的阶乘,但实际输出的是累加值3、5、6的阶乘。

错误代码

n = int(input("Enter a number: "))
s = 0
fact = 1
a = 1
for i in range(len(str(n))):
    r = n % 10
    s += r
    n //= 10
    while a <= s:
        fact *= a
        a += 1

    print('The factorial of', s, 'is', fact)

实际运行输出

Enter a number: 123
The factorial of 3 is 6
The factorial of 5 is 120
The factorial of 6 is 720

问题分析

  • 核心逻辑错误:代码中用s += r累加了每一位数字,导致每次计算的是累加和的阶乘,而非当前单个数字r的阶乘,完全偏离需求。
  • 辅助变量问题:fact和a作为全局变量未在每次循环重置,虽然累加计算的阶乘数值正确,但逻辑不符合预期。

修正方案

需要针对每一位数字单独计算阶乘,每次循环处理单个数字,重置阶乘相关变量或单独计算当前数字的阶乘。

方案1:按输入顺序输出各位阶乘(直观写法)

直接遍历数字的字符串形式,正序处理每一位:

n = input("Enter a number: ")
for digit_char in n:
    digit = int(digit_char)
    fact = 1
    for i in range(1, digit + 1):
        fact *= i
    print(f'The factorial of {digit} is {fact}')

运行输出:

Enter a number: 123
The factorial of 1 is 1
The factorial of 2 is 2
The factorial of 3 is 6

方案2:修正原代码逻辑(保留取余方式)

如果要保留原代码的取余拆分数字方式,需去掉累加逻辑,每次单独计算当前位的阶乘:

n = int(input("Enter a number: "))
for i in range(len(str(n))):
    r = n % 10
    n //= 10
    # 单独计算当前数字r的阶乘
    fact = 1
    a = 1
    while a <= r:
        fact *= a
        a += 1
    print(f'The factorial of {r} is {fact}')

运行输出(注意:取余会从个位开始输出):

Enter a number: 123
The factorial of 3 is 6
The factorial of 2 is 2
The factorial of 1 is 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:04:42