【问题标题】:How do I get decimals values without rounding them off如何在不四舍五入的情况下获得小数值
【发布时间】:2021-03-25 01:24:25
【问题描述】:

如何将两个数字相加并在最终答案中保留小数位?下面是执行此操作的代码,但它不起作用。

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

【问题讨论】:

  • float(i) 不是您要添加的号码。
  • 也许你的意思是j = float(l1[i])。或者 for 循环 for i in li:

标签: python python-3.x file floating-point decimal


【解决方案1】:

我想你想这样做:

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)

【讨论】:

    猜你喜欢
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多