码迷,mamicode.com
首页 > 编程语言 > 详细

python作为计算器(数学用法)

时间:2018-02-16 12:04:04      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:class   post   苹果   put   练习   floor   增强   3.1   计算   

1.基本的加减乘除与取余运算

>>> print(5+10)
15
>>> print(5-10)
-5
>>> print(5*10)
50
>>> print(10/5)
2.0
>>> print(5%3)
2

 

2.求n次方与求平方根

>>> print(5%3)
2
>>> print(5**3)
125
>>> print(125**(1/3))
5.0
>>> print(2**4)
16
>>> print(16**(1/2))
4.0
>>>

 

3.math函数库的使用

引入math库并查看PI的值

>>> import math
>>> math.pi
3.141592653589793

 

(1)求正弦余弦函数

>>> math.sin(math.pi/2)
1.0
>>> math.cos(math.pi/4)
0.7071067811865476
>>> math.tan(math.pi/4)
0.9999999999999999
>>>

 

(2)上取整与下取整

>>> math.floor(5.225)
5
>>> math.ceil(5.225)
6

 

 

 

 

 

练习:一道应用题

苹果5元一斤,葡萄15元一斤,卖了一斤苹果2.5斤葡萄,问总共花了多少钱?

解:

>>> #苹果花费
...
>>> #葡萄花费
...
>>> print(5*1)
5
>>> print(15*2.5)
37.5
>>> #总花费
...
>>> print(5+37.5)
42.5

 

 

解法二:

>>> apple_price = 5
>>> apple_weight = 1
>>> putao_price = 15
>>> putao_weight = 2.5
>>> #苹果花费
... print(apple_price*apple_weight)
5
>>> #葡萄花费
... print(putao_price*putao_weight)
37.5
>>> #总花费
... print(5+37.5)
42.5
>>>

 

 

>>> putao_toast = putao_price*putao_weight
>>> apple_toast = apple_price*apple_weight
>>> print(putao_toast + apple_toast)
42.5

 

解法三:利用增强的格式化字符串函数 format

>>> "葡萄的总价是{},苹果的总价是{},总共花费{}".format(putao_toast,apple_toast,pu
tao_toast+apple_toast)
葡萄的总价是37.5,苹果的总价是5,总共花费42.5

 

{}代表取参数,有几个{},传几个参数,按顺序取参数

 

python作为计算器(数学用法)

标签:class   post   苹果   put   练习   floor   增强   3.1   计算   

原文地址:https://www.cnblogs.com/qlqwjy/p/8450093.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!