说X必须是对数函数中的值?

时间:2018-09-21 14:10:10

标签: python math logarithm

我有以下代码:

import math
q = input("Is there a square root in the function? (y,n) ")
if q == "y":
  base = input("base? ")
  x_value = input("x? ")
  print (math.log(math.sqrt(base),x_value))
else:
  base_2 = input("base? ")
  x_value_2 = input("x? ")
  print (math.log(base_2, x_value_2))

运行代码时,它说math.log()中的第二个值必须是数字。如果我只使用分配给它的变量,那不行吗?

1 个答案:

答案 0 :(得分:1)

input()返回一个字符串。您应该使用float()构造函数将用户输入转换为浮点数:

import math
q = input("Is there a square root in the function? (y,n) ")
if q == "y":
  base = float(input("base? "))
  x_value = float(input("x? "))
  print (math.log(math.sqrt(base),x_value))
else:
  base_2 = float(input("base? "))
  x_value_2 = float(input("x? "))
  print (math.log(base_2, x_value_2))