提问者:小点点

接收到5^2的错误结果


我试图用Python计算5^2,结果是7。 我正在附加我的代码片段。 知道发生了什么事吗?

我试过:

math.pow(a,b)
a**b
eval(str(x))

我收到了同样的结果7他们每个人。 我还引进了数学。

这是我正在使用的当前代码:

question = ["5^2"]
def checkExponent(self, question):
     for i in range(len(question)):
          if question[i] == "^":
               return(math.pow(int(question[i-1]), int(question[i+1])))

def calculate(self):
     temp = 0
     for i in range(len(self.problemArray)):
          if self.checkExponent(self.problemArray[i]) == "":
               temp = self.checkExponent(self.problemArray[i])
          else:
               temp = eval(str(self.problemArray[i]))
          self.answerArray.append(temp)
          temp = 0

我最初使用的是:

def calculate(self):
     temp = 0
     for i in range(len(self.problemArray)):
          temp = eval(str(self.problemArray[i]))
          self.answerArray.append(temp)
          temp = 0

共2个答案

匿名用户

^是按位异或运算符。 如果您将其eval(),则5^2将变为0b101 xor 0b010,因此0b111=7。

使用a**b,避免使用eval。

匿名用户

Python充满了一堆令人惊叹的东西供程序员使用,为了计算5^2,只需编写5**2我不明白为什么你坚持要用这么长的代码来完成这么简单的操作。 我承认这不是你问题的完美答案,尽管这是对你有益的更优化的方法