首页 > 解决方案 > 如何使输出数字与阶乘结果匹配

问题描述

我得到了一个使用循环制作程序的任务。用户输入一个 1-98 的数字,然后输出是该数字的阶乘。如果用户输入的数字不是上述数字,则要求用户重新输入适当的数字。现在当用户输入合适时,输出的输出与阶乘结果不匹配。

这是那个错误的图片

这是代码

num = int(input("Input Number (1-98) : "))

    Factorial = 1
    for a in range(1,num+1):
        if 0 < num < 99:
            Factorial = Factorial*a
        else :
            print("input does not match, Repeat input (1-98)")
            num = int(input("Input Number (1-98) :"))
    
    print ("The factorial of", num, "is", Factorial)

你能帮我解决这个问题吗?

标签: pythonloopsfor-loopoutputfactorial

解决方案


您必须将输入部分计算部分分开

num = -1
while not (0 < num < 99):
    num = int(input("Input Number (1-98) :"))

Factorial = 1
for a in range(1, num + 1):
    Factorial = Factorial * a

print("The factorial of", num, "is", Factorial)

原因是

  • 你输入99
  • 循环运行所有值,计算阶乘直到 98
  • else"input does not match"
  • 循环是否结束,但您将计算的阶乘保存在内存中并从那里开始

推荐阅读