【问题标题】:How do I make sure all of my values are computed in my loop?如何确保我的所有值都在我的循环中计算?
【发布时间】:2019-09-18 14:17:05
【问题描述】:

我正在执行“保留零钱任务”,我将购买的金额四舍五入,然后将零钱添加到储蓄账户中。但是,循环不会遍历我的外部文本文件中的所有值。它只计算最后一个值。我尝试拆分文件,但它给了我一个错误。可能是什么问题?我的外部文本文件是这样的:

10.90 13.59 12.99 (每个在不同的行)

def main():

account1 = BankAccount()                  
file1 = open("data.txt","r+")       # reading the file, + indicated read and write
s = 0       # to keep track of the new savings
for n in file1:
    n = float(n)    #lets python know that the values are floats and not a string
    z= math.ceil(n)      #rounds up to the whole digit
    amount = float(z-n)         # subtract the rounded sum with actaul total to get change
    print(" Saved $",round(amount,2), "on this purchase",file = file1)
    s = amount + s
    x = (account1.makeSavings(s))

【问题讨论】:

    标签: python loops class object


    【解决方案1】:

    我很确定这是因为您正在打印已保存到文件中的金额。通常,您不希望更改正在迭代的对象的长度,因为这可能会导致问题。

    account1 = BankAccount()                  
    file1 = open("data.txt","r+")       # reading the file, + indicated read and write
    s = 0       # to keep track of the new savings
    amount_saved = []
    for n in file1:
        n = float(n)    #lets python know that the values are floats and not a string
        z= math.ceil(n)      #rounds up to the whole digit
        amount = float(z-n)         # subtract the rounded sum with actaul total to get change
        amount_saved.append(round(amount,2))
        s = amount + s
        x = (account1.makeSavings(s))
    for n in amount_saved:
        print(" Saved $",round(amount,2), "on this purchase",file = file1)
    

    这将在您完成迭代后在文件末尾打印您保存的金额。

    【讨论】:

      猜你喜欢
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 2022-11-12
      • 2017-07-24
      • 2021-03-27
      • 1970-01-01
      相关资源
      最近更新 更多