我正在尝试解决 Finger Exercise 3.1,但我不知道我在这里做错了什么。当我输入“1”作为整数时,它返回 0 和 0。
我是编程和 Stack Overflow 的新手,所以我不确定我是否正确地执行此操作,但我想我会试一试。
问题是: 编写一个程序,要求用户输入一个整数并打印两个整数, root 和 pwr,使得 0 < pwr < 6 且 root**pwr 等于输入的整数 由用户。如果不存在这样的整数对,它应该打印一条消息给 那种效果。
到目前为止,这是我的解决方案:
x = int(raw_input('Enter a positive integer: '))
root = 0
pwr = 0
while pwr < 6:
pwr += 1
while root**pwr < x:
root += 1
if root**pwr == x:
print "The root is " + str(root) + " and the power is " + str(pwr)
else:
print "No such pair of integers exists."
如何修复我的代码,使其返回正确的整数? 我在这里做错了什么?我缺少什么逻辑?
最佳答案
一个问题是,虽然您确实有结束循环的条件,但它们总是会一直达到最大允许条件。您可以使用 break
或如图所示,通过在函数中使用 return
来解决该问题。此外,不使用计数器,而是使用 xrange()
函数(Python 3 中的 range()
)。
>>> def p(num):
... for power in xrange(6):
... for root in xrange(num/2+1):
... if root**power==num:
... return root, power
...
>>> r, pwr = p(8)
>>> print 'The root is', r, 'and the power is', pwr
The root is 2 and the power is 3
关于python - 使用 Python 进行计算和编程介绍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30202740/