【问题标题】:In which case round(a, 2) and f'{a:.2f}' will give a different result? Python在哪种情况下 round(a, 2) 和 f'{a:.2f}' 会给出不同的结果? Python
【发布时间】:2021-03-09 09:38:34
【问题描述】:

我有以下任务:

乔治今晚要请客,他决定买鲣鱼、竹荚鱼和贻贝。他去鱼市买了几公斤。您在控制台中以美元输入鲭鱼和鲱鱼的价格。您还可以输入鲣鱼、竹荚鱼和贻贝的数量(以 kg 为单位)。如果鱼市的价格是:乔治需要多少钱来支付账单:

  • 鲣鱼 - 比鲭鱼贵 60%
  • 竹荚鱼 - 比鲱鱼贵 80%
  • 贻贝 - 7.50 美元/公斤

输入:

  • 第一行:鲭鱼价格(浮点数)
  • 第二行:鲱鱼价格(浮点数)
  • 第三行:鲣鱼的数量,以公斤为单位(浮点数)
  • 第四行:竹荚鱼数量,单位为公斤(浮点数)
  • 第五行:贻贝的数量,以公斤为单位(整数)

输出: 结果。四舍五入到小数点后第二位的浮点数。

我的代码是:

sprats_price = float(input())
bonito_kg = float(input())
horse_mackerel_kg = float(input())
mussels_kg = int(input())
 
bonito_price = mackerel_price * 1.6
horse_mackerel_price = sprats_price * 1.8
mussels_price = 7.5
 
bonito_total = bonito_kg * bonito_price
hours_mackerel_total = horse_mackerel_kg * horse_mackerel_price
mussels_total = mussels_kg * mussels_price
 
total = bonito_total + hours_mackerel_total + mussels_total
print(round(total, 2))

我得到了 80/100 分。

当我改变时

print(round(total, 2))

print(f'{total:.2}')

我得到了 100/100。

所以我想知道在哪种情况下会有不同的结果?

有 3 个示例输入/输出:

  • 示例输入:

  • 6.90

  • 4.20

  • 1.5

  • 2.5

  • 1

  • 输出: 42.96

  • 示例输入:

  • 5.55

  • 3.57

  • 4.3

  • 3.6

  • 7

  • 输出:

  • 113.82

  • 示例输入:

  • 7.79

  • 5.35

  • 9.3

  • 0

  • 0

  • 输出:

  • 115.92

总共有 10 个测试。

提前致谢。

附:会不会是任务的条件有错误?

【问题讨论】:

    标签: python rounding f-string


    【解决方案1】:

    首先你的问题是关于a:.2f,但你写的是print(f'{total:.2}'),所以我要使用.2f

    如果数字有尾随零,

    In [1]: x = 5.7899
    
    In [2]: round(x,2)
    Out[2]: 5.79
    
    In [3]: f'{x:.2f}'
    Out[3]: '5.79'
    
    In [4]: x = 5.7
    
    In [5]: round(x,2)
    Out[5]: 5.7
    
    In [6]: f'{x:.2f}'
    Out[6]: '5.70'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-23
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 2021-10-21
      • 2018-01-06
      相关资源
      最近更新 更多