我们应该创建一个程序,对于正整数n,n的阶乘
这是我的代码。
def factorial(num):
F = 0
x = 1
factor = 1
while (F <= num):
for i in range(1,x + 1):
factor = (factor * i)
if (F>=num):
return x
else:
x = x+1
print("The answer is", x)
F = factor
factorial_cap(24) 我只是使用print语句来查看输出是什么,它一直在给我 答案是2 答案是4 答案是8, 虽然正确的答案应该是4,但我无法阻止它循环而只返回值4
答案 0 :(得分:2)
它继续打印&#34;答案的原因是&#34; string是print
语句直接放在while循环中,所以它会触发每次新的尝试。
尝试这种方法(Python 2.7.8):
def factorial_cap(num):
print "Input number:", num
F = 1
x = 1
while (F < num):
x += 1
F *= x
print "The answer is:", x
return x
for t in xrange(0,30):
factorial_cap(t)
print
或者这个(效率较低):
def factorial(num):
res = 1
for i in xrange(1,num+1):
res *= i
return res
def factorial_cap(num):
print "Input number:", num
F = 0
x = 0
while (F < num):
x = x+1
F = factorial(x)
print "The answer is:", x
return x
for t in xrange(0,30):
factorial_cap(t)
print