这个问题在这里已有答案:
将浮动限制为两个小数点 19个答案我在Python中编写了一个非常简单的代码。 我需要以0.1步长打印1到5之间的所有数字(包括1和5 )。 整数应该没有后缀.0 ,即输出应该是:
0 0.1 0.2 ... 1 1.1 ... ... 5这是我的代码:
for i in range(0,51): if i%10==0: z=int(i/10) print (z) else: print (i*0.1)这是我的输出:
0 0.1 0.2 0.30000000000000004 0.4 0.5 0.6000000000000001 0.7000000000000001 0.8 0.9 1 1.1 1.2000000000000002 1.3 1.4000000000000001 1.5 1.6 1.7000000000000002 1.8 1.9000000000000001 2 2.1 2.2 2.3000000000000003 2.4000000000000004 2.5 2.6 2.7 2.8000000000000003 2.9000000000000004 3 3.1 3.2 3.3000000000000003 3.4000000000000004 3.5 3.6 3.7 3.8000000000000003 3.9000000000000004 4 4.1000000000000005 4.2 4.3 4.4 4.5 4.6000000000000005 4.7 4.800000000000001 4.9 5我不需要所有这些零.000000001 。
This question already has an answer here:
Limiting floats to two decimal points 24 answersI wrote a very simple code in Python. I need to print all the numbers between 1 and 5 (including 1 and 5) in steps of 0.1. The integers should be without the suffix .0, i.e. the output should be:
0 0.1 0.2 ... 1 1.1 ... ... 5Here is my code:
for i in range(0,51): if i%10==0: z=int(i/10) print (z) else: print (i*0.1)Here is my output:
0 0.1 0.2 0.30000000000000004 0.4 0.5 0.6000000000000001 0.7000000000000001 0.8 0.9 1 1.1 1.2000000000000002 1.3 1.4000000000000001 1.5 1.6 1.7000000000000002 1.8 1.9000000000000001 2 2.1 2.2 2.3000000000000003 2.4000000000000004 2.5 2.6 2.7 2.8000000000000003 2.9000000000000004 3 3.1 3.2 3.3000000000000003 3.4000000000000004 3.5 3.6 3.7 3.8000000000000003 3.9000000000000004 4 4.1000000000000005 4.2 4.3 4.4 4.5 4.6000000000000005 4.7 4.800000000000001 4.9 5I don't need all this zeros .000000001.
最满意答案
利用Python的字符串格式化功能,您可以将整个循环减少到一行:
for i in range(0, 51): print('{:.{deci}f}'.format(i*0.1, deci=min(1, i%10)))输出:
0 0.1 0.2 ... 0.8 0.9 1 1.1 1.2 ... 1.8 1.9 2 2.1 2.2 ... 4.8 4.9 5说明
这给你0为i倍数为10,其他为1倍数:
>>> i = 10 >>> min(1, i%10) 0 >>> i = 8 >>> min(1, i%10) 1现在,您可以将此用作关键字参数deci来确定输出中的小数位数:
>>> '{:.{deci}f}'.format(1.99, deci=1) '2.0' >>> '{:.{deci}f}'.format(1.99, deci=0) '2'Taking advantage of Python's string formatting capabilities, you can reduce your whole loop to one line:
for i in range(0, 51): print('{:.{deci}f}'.format(i*0.1, deci=min(1, i%10)))Output:
0 0.1 0.2 ... 0.8 0.9 1 1.1 1.2 ... 1.8 1.9 2 2.1 2.2 ... 4.8 4.9 5Explanation
This gives you 0 for multiples of 10 for i and 1 for others:
>>> i = 10 >>> min(1, i%10) 0 >>> i = 8 >>> min(1, i%10) 1Now, you can use this for the keyword argument deci to determine the number of decimals in your output:
>>> '{:.{deci}f}'.format(1.99, deci=1) '2.0' >>> '{:.{deci}f}'.format(1.99, deci=0) '2'更多推荐
发布评论