[英]How to create a program that does exponentiation using nested while loops in python?
x=eval(input('Enter a number greater than 1: '))
e=eval(input('Enter an exponenet greater than 1: '))
i=2
j=1
power=1
while i <= x:
while j <=e:
power=power*i
j=j+1
print(i, 'to the power',e, '=', power)
i=i+1
到目前为止,这是我的代码:此代码的输出是输入 5 和 3 时
2 to the power 3 = 8
3 to the power 3 = 8
4 to the power 3 = 8
5 to the power 3 = 8
我需要输出为:
2 to the power 3 = 8
3 to the power 3 = 27
4 to the power 3 = 64
5 to the power 3 = 125
我需要使用嵌套的 while 循环,不能使用求幂运算符 (**)。 我将不胜感激,并在此先感谢您!
在进入嵌套循环之前,您需要重置power
和j
。
x=eval(input('Enter a number greater than 1: '))
e=eval(input('Enter an exponenet greater than 1: '))
i=2
while i <= x:
j = 1
power = 1
while j <=e:
power=power*i
j=j+1
print(i, 'to the power',e, '=', power)
i=i+1
这只能通过加法来完成,对于x**power
:
value = x #ex 3**3
temp = x
result = x
while power > 1:
while value > 1:
temp += result #1st loop: 3 + 3 + 3 = 9
value -= 1 #2nd loop 9 + 9 + 9 = 27
result = temp
value = x
power -= 1
print(f"{x} to the power of {power} is {result}")
但是请注意,如果power = 0
失败,就像power = -1
。
更“低技术”的方法是依次定义函数后继、加法、乘法和求幂。
def succ(x):
return x
def add(x, y):
result = x
while y > 0:
result = succ(x)
y -= 1
return result
def mult(x, y):
result = x
while y > 1:
result = add(result, x)
y -= 1
return result
def exp(x, y):
result = 1
while y > 0:
result = mult(result, x)
y -= 1
return result
所有四个都是一元数上原始递归函数的规范示例。 它们最好使用递归或for
循环来实现。
有关下一个(超)操作,请参阅Knuth 的向上箭头符号。
干得好!
您的代码唯一的问题是变量没有重新初始化为 1。我为您修复了它!
x=eval(input('Enter a number greater than 1: '))
e=eval(input('Enter an exponenet greater than 1: '))
i=2
j=1
power=1
while i <= x:
while j <=e:
power = power * i
j=j+1
print(i, 'to the power',e, '=', power)
power = 1
j = 1
i = i + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.