如何在不四舍五入的情况下获得小数值
How do I get decimals values without rounding them off
如何将两个数字相加并在最终答案中保留它们的小数位?下面是执行此操作的代码,但它不起作用。
import re
cnt=0
s=0
l1= []
with open('C://Users/S/Documents/ok5.txt') as f:
for i in f:
if i.startswith('X-DSPAM-Confidence:'):
x = re.findall('\d*?\.\d+',i)
l1.append(x)
cnt+=1
for i in range(0,len(l1)):
j = float(i)
s += j
print(l1)
print(s)
我得到的输出是:
[['0.5454'], ['0.5677']]
1.0
但是,当我尝试下面的简单代码时,它给出了正确的答案:
a = 0.5454
b = 0.5677
c = float(a+b)
print(c)
这个输出是:
1.1131
我想你想这样做:
import re
cnt=0
s=0
l1= []
with open('C://Users/S/Documents/ok5.txt') as f:
for i in f:
if i.startswith('X-DSPAM-Confidence:'):
x = re.findall('\d*?\.\d+',i)
l1.append(x)
s += float(x[0]) # You could just add it here, which improves time complexity
cnt+=1
print(l1)
print(s)
如何将两个数字相加并在最终答案中保留它们的小数位?下面是执行此操作的代码,但它不起作用。
import re
cnt=0
s=0
l1= []
with open('C://Users/S/Documents/ok5.txt') as f:
for i in f:
if i.startswith('X-DSPAM-Confidence:'):
x = re.findall('\d*?\.\d+',i)
l1.append(x)
cnt+=1
for i in range(0,len(l1)):
j = float(i)
s += j
print(l1)
print(s)
我得到的输出是:
[['0.5454'], ['0.5677']]
1.0
但是,当我尝试下面的简单代码时,它给出了正确的答案:
a = 0.5454
b = 0.5677
c = float(a+b)
print(c)
这个输出是:
1.1131
我想你想这样做:
import re
cnt=0
s=0
l1= []
with open('C://Users/S/Documents/ok5.txt') as f:
for i in f:
if i.startswith('X-DSPAM-Confidence:'):
x = re.findall('\d*?\.\d+',i)
l1.append(x)
s += float(x[0]) # You could just add it here, which improves time complexity
cnt+=1
print(l1)
print(s)