【问题标题】:Why is my basic exponent function not working? [closed]为什么我的基本指数函数不起作用? [关闭]
【发布时间】:2020-01-08 21:27:05
【问题描述】:

我正在尝试为指数函数获取输入,但它没有给出输出。

def exp_func(base,exponent):
    result = 1
    for index in range(0,exponent):
        result*=base
    return result

base = float(input("Enter base:"))
exponent = float(input("Enter exponent:"))

print(exp_func(base,exponent))

但是没有任何输入它工作正常。

def exp_func(base,exponent):
    result = 1
    for index in range(0,exponent):
        result*=base
    return result

print(exp_func(2,3))

有什么问题?

【问题讨论】:

  • 请举例说明当您按预期运行时会发生什么。
  • 尝试将float 更改为int。在您的第一个未工作示例中,您使用浮点数,在第二个工作中使用 - int

标签: python exponent


【解决方案1】:

Range 需要整数类型,而不是浮点数。

range(10)
#range(1,10)
range(10.0)
#TypeError: 'float' object cannot be interpreted as an integer

尝试将输入更改为 int。您的实现不适用于非整数。

def exp_func(base,exponent):
    result = 1
    for index in range(0,exponent):
        result*=base
    return result

base = float(input("Enter base:"))
exponent = int(input("Enter exponent:"))

print(exp_func(base,exponent))

另外,如果您不知道 ** 运算符,它会计算指数

def exp_func(base,exponent):
    return base ** exponent

这适用于浮点数。

【讨论】:

  • 我差点忘了** 运算符,你提醒我把它添加到我的答案中哈哈
【解决方案2】:

尝试将float(input('Enter Base'))float(input('Enter Base')) 更改为int(input('Enter Base'))int(input('Enter Base')),因为如果不包含小数,float() 函数会自动将.0 添加到您的数字中。

这是因为range() 函数不能与小数一起使用,因此执行上述操作可以解决您的问题。

你的问题不清楚,所以这是我能给你的最佳答案。如果您想要更好的答案,请更改您的问题。

编辑:另外,如果您想要使用小数的指数,您可以使用 ** 运算符。示例:

3 ** 4
RETURNS: 81

【讨论】:

  • float("3") 确实有效。唯一的问题在于range 的论点。 (没有投反对票,顺便说一句)
  • 好的,我已经改变了我的答案。我认为@oli5679 被否决了? (无罪)
  • 哈哈,保持选民匿名是件好事,但我没有投反对票 :)
  • 感谢将输入更改为 int() 有效。
  • 如果您的问题已得到解答,请检查其中一个答案以通知社区该问题已得到解答:)
猜你喜欢
  • 2020-09-05
  • 2023-03-04
  • 2020-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多