视频打印次数求教
>>> i = 0>>> while i < 1:
i = i+0.1
print("Cl is my baby!")
Cl is my baby!
Cl is my baby!
Cl is my baby!
Cl is my baby!
Cl is my baby!
Cl is my baby!
Cl is my baby!
Cl is my baby!
Cl is my baby!
Cl is my baby!
Cl is my baby!
请问为什么是打印11次呢 而我换成整数就是10次
>>> i = 0
>>> while i < 10:
i = i+1
print(i)
1
2
3
4
5
6
7
8
9
10 浮点数运算有误差的,第十次是0.9999999,也当小于1了
>>> i = 0
>>> while i < 1:
i = i+0.1
print("Cl is my baby!",i)
Cl is my baby! 0.1
Cl is my baby! 0.2
Cl is my baby! 0.30000000000000004
Cl is my baby! 0.4
Cl is my baby! 0.5
Cl is my baby! 0.6
Cl is my baby! 0.7
Cl is my baby! 0.7999999999999999
Cl is my baby! 0.8999999999999999
Cl is my baby! 0.9999999999999999
Cl is my baby! 1.0999999999999999 i = 0
while i < 1:
i = round(i+0.1, 1) # 使用 round() 函数减少浮点精度误差
print("Cl is my baby!")Cl is my baby! # 0.1
Cl is my baby! # 0.2
Cl is my baby! # 0.3
Cl is my baby! # 0.4
Cl is my baby! # 0.5
Cl is my baby! # 0.6
Cl is my baby! # 0.7
Cl is my baby! # 0.8
Cl is my baby! # 0.9
Cl is my baby! # 1.0
页:
[1]