当成计算器使用¶
四则运算¶
print(100 * 3 - 20 + 2 ** 3)
除法需要注意¶
print(222 / 333) # 普通除法
print(222 // 333) # 取整除法
使用数学函数¶
导入数学函数包:
import math
根式¶
计算根式,比如计算\sqrt 3
print(math.sqrt(3))
三角函数¶
print(math.cos(math.pi / 3))
print(math.sin(math.pi / 6))
取整¶
取整大致分为3种,向上取整,四舍五入,向下取整。接下来分别来看。
print(math.ceil(2.4)) # 向上取整
print(round(1.2)) # 四舍五入
print(round(1.7)) # 四舍五入
print(math.floor(1.7)) # 向下取整
print(math.floor(1.2)) # 向下取整
指数计算¶
其实指数的计算可以运算符**
,,比如3^4可以写成3 ** 4
.数学包里面也提供了函数。
print(math.pow(3, 4))
总结
把Python当成计算器使用,功能是非常强大的。数学包提供了非常多的计算函数,方便调用。本节内容首次用到了包的导入。导入包,其实是借助别人实现的算法。