pow 运算符的计算错误 [英] Calculation error with pow operator

查看:47
本文介绍了pow 运算符的计算错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

print (-2 ** 2) 应该返回什么?根据我的计算,它应该是 4,但解释器返回 -4.
这是 Python 的东西还是我的数学很糟糕?

解决方案

根据 docs** 的优先级高于 -,因此你的代码等价于 -(2 ** 2).要获得所需的结果,您可以将 -2 放在括号中

<预><代码>>>>(-2) ** 24

或使用内置的pow 函数

<预><代码>>>>战俘(-2, 2)4

math.pow 函数(返回 float 值)

<预><代码>>>>导入数学>>>math.pow(-2, 2)4.0

What should print (-2 ** 2) return? According to my calculations it should be 4, but interpreter returns -4.
Is this Python's thing or my math is that terrible?

解决方案

According to docs, ** has higher precedence than -, thus your code is equivalent to -(2 ** 2). To get the desired result you could put -2 into parentheses

>>> (-2) ** 2
4

or use built-in pow function

>>> pow(-2, 2)
4

or math.pow function (returning float value)

>>> import math
>>> math.pow(-2, 2)
4.0

这篇关于pow 运算符的计算错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆