2016-09-24 105 views
0

我刚启动Python 2.7。 我想做一个程序,执行电源功能(使用循环),而不使用导入。数学 我想我得到它,除了我的程序不执行负指数。 只输出为1. 这是我到目前为止。使用循环的电源功能

decimal=float(input('Enter the base number:')) 
integer=int(input('Enter the exponent number:')) 

def power_function(decimal, integer): 
    num=1 
    for function in range(integer): 
     if integer>0: 
      num=num*decimal 
     if integer<0: 
      num=1/(num*decimal) 
    return num 
print power_function(decimal, integer) 
+0

'范围( )负数是空的列表,因此永远不会进入循环。 – AChampion

+0

啊!我明白了,那我该怎么办?负数时是否需要使其不进入循环? – jnkim0715

回答

2

根据负值的范围进行修复。

def power_function(decimal, integer): 
    num=1 
    if integer>0: 
     for function in range(integer): 
      num=num*decimal 
    if integer<0: 
     num=1.0 # force floating point division 
     for function in range(-integer): 
      num=num/decimal 
    return num 
+0

我试过你的方法,但它仍然给我输出1 – jnkim0715

+0

对不起,当我重新编辑帖子时,我复制了你的'num = 1 /(num * decimal)'表达式而不是正确的'num = num /小数“表达 –

+0

非常感谢!有用。快速的问题,虽然..为什么我需要把“num = 1”作为一个全球性的术语?在线2?我仍然无法掌握循环的想法 – jnkim0715

0

简单的解决方法是使用abs(integer)range

def power_function(decimal, integer): 
    num = 1 
    for function in range(abs(integer)): 
     num = num*decimal if integer > 0 else num/decimal 
    return num 

power_function(2, 2) 
# 4 
power_function(2, -2) 
# 0.25 

或者只是使用减少:

def power_function(decimal, integer): 
    op = (lambda a, b: a*b) if integer > 0 else (lambda a, b: a/b) 
    return reduce(op, [decimal]*abs(integer), 1) 

power_function(3, 3) 
# 27 
+0

我只允许使用循环和条件。我不允许使用任何导入类型 – jnkim0715

+0

您也可以使用匿名函数执行此操作 - 无需导入。 – AChampion

+0

如何?你介意给我看源代码吗?我绝对是初学者......即使你告诉我该怎么做,我也不能理解它,因为我不知道很多东西。 – jnkim0715

1

我已经做了一些调整

def power_function (decimal, integer): 

    num = 1 

    for function in range (abs(integer)): 
     if integer > 0: 
      num *= decimal 

     if integer < 0: 
      num *= 1.0/decimal 

     if integer == 0: 
      num = 1 

    return num