python - 如何使输出数字与阶乘结果匹配
问题描述
我得到了一个使用循环制作程序的任务。用户输入一个 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)
你能帮我解决这个问题吗?
解决方案
您必须将输入部分和计算部分分开
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"
- 循环是否结束,但您将计算的阶乘保存在内存中并从那里开始
推荐阅读
- node.js - NodeJS 承诺 Firebase
- docker - 在 Ubuntu 18 上重新启动后找不到 Docker
- javascript - module.exports 中的 getter 和 es6 样式导入(反应导航器)
- python - 具有所需帧率的 imshow() 与 opencv
- java - Spring Boot 在运行时获取主类的名称
- php - Symfony - 无法运行创建的控制台命令
- c# - 从字符串中获取数字和字符串
- c# - 如何显示和隐藏多个表单?
- javascript - 如何在 React 中通过 ID="" 选择一个 React 组件(不使用 ref)
- c - 尝试编译 xf86drm.h 示例