博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 数据类型 -- 数字
阅读量:4050 次
发布时间:2019-05-25

本文共 1653 字,大约阅读时间需要 5 分钟。

– Start


整数(int)

整数没有精度限制,具有无穷大小。

# 十进制整数n = 255n = int(255)print(n)# 二进制以 0b 开头n = 0b11111111n = bin(255)n = int('11111111', 2)print(n)# 八进制以 0o 开头n = 0o377n = oct(255)n = int('377', 8)print(n)# 十六进制以 0x 开头, a,b,c,d,e,f 不区分大小写n = 0xFFn = hex(255)n = int('FF', 16)print(n)

浮点数(float)

浮点数精度和 C 双精度相同。

# 定义浮点数n = 3.1415n = 3.n = .1415n = 3.14e-10 # e不区分大小写n = float('3.1415')print(n)

复数(complex)

复数由实部和虚部组成。

# 定义复数n = 3+4jn = 3.0+4.0jn = 3jn = complex(3, 4)print(n)# 访问实部和虚部print(n.real)print(n.imag)

算术运算

# 算术运算x = 3y = 2r = x + y #加print(r)r = x - y #减print(r)r = x * y #乘print(r)r = x / y #除print(r)r = x // y #除:丢弃小数部分print(r)r = x ** y #幂,相当于2的3次方print(r)r = x % y #余print(r)

四舍五入函数

Python 支持下面的四舍五入函数。

math.ceil  # 向上舍入math.floor # 向下舍入round      # 四舍五入math.trunc # 舍去小数

我们来测试一下。

import mathdef my_print(n):	print(str(n).ljust(7) + str(math.ceil(n)).ljust(7) + str(math.floor(n)).ljust(7) + str(round(n)).ljust(7) + str(math.trunc(n)).ljust(7))print('NUM    CEIL   FLOOR  ROUND  TRUNC')my_print(5.5)my_print(2.5)my_print(1.6)my_print(1.1)my_print(1)my_print(-1)my_print(-1.1)my_print(-1.6)my_print(-2.5)my_print(-5.5)

看看下面的结果吧。

NUM    CEIL   FLOOR  ROUND  TRUNC5.5    6      5      6      52.5    3      2      2      21.6    2      1      2      11.1    2      1      1      11      1      1      1      1-1     -1     -1     -1     -1-1.1   -1     -2     -1     -1-1.6   -1     -2     -2     -1-2.5   -2     -3     -2     -2-5.5   -5     -6     -6     -5

相关函数

# 求绝对值r = abs(-3)print(r)# 幂,相当于2的3次方r = pow(2, 3)print(r)# 返回 a/b 和 a%br = divmod(3, 2)print(r)

– 更多参见:

– 声 明:转载请注明出处
– Last Updated on 2018-09-05
– Written by ShangBo on 2017-04-23
– End

你可能感兴趣的文章
CCF 分蛋糕
查看>>
解决python2.7中UnicodeEncodeError
查看>>
小谈python 输出
查看>>
Django objects.all()、objects.get()与objects.filter()之间的区别介绍
查看>>
python:如何将excel文件转化成CSV格式
查看>>
机器学习实战之决策树(一)
查看>>
机器学习实战之决策树二
查看>>
[LeetCode By Python]7 Reverse Integer
查看>>
[LeetCode By Python]121. Best Time to Buy and Sell Stock
查看>>
[LeetCode By Python]122. Best Time to Buy and Sell Stock II
查看>>
[LeetCode By Python]125. Valid Palindrome
查看>>
[LeetCode By Python]136. Single Number
查看>>
Android/Linux 内存监视
查看>>
Android2.1消息应用(Messaging)源码学习笔记
查看>>
MPMoviePlayerViewController和MPMoviePlayerController的使用
查看>>
CocoaPods实践之制作篇
查看>>
[Mac]Mac 操作系统 常见技巧
查看>>
苹果Swift编程语言入门教程【中文版】
查看>>
捕鱼忍者(ninja fishing)之游戏指南+游戏攻略+游戏体验
查看>>
iphone开发基础之objective-c学习
查看>>