在哪种情况下 round(a, 2) 和 f'{a:.2f}' 会给出不同的结果? Python
In which case round(a, 2) and f'{a:.2f}' will give a different result? Python
我有以下任务:
乔治今晚要请客,他决定买鲣鱼、竹荚鱼和贻贝。他去鱼市买了几公斤。您在控制台中以美元输入鲭鱼和西鲱的价格。您还可以输入以千克为单位的鲣鱼、竹荚鱼和贻贝的数量。如果鱼市的价格是:
,乔治需要多少钱来买单?
- 鲣鱼 - 比鲭鱼贵 60%
- 竹荚鱼 - 比西鲱贵 80%
- 贻贝 - 7.50 USD/kg
输入:
- 第一行:鲭鱼价格(浮点数)
- 第二行:西鲱价格(浮点数)
- 第三行:鲣鱼的数量(浮点数)
- 第四行:竹荚鱼的数量(公斤)
- 第五行:以公斤为单位的贻贝数量(整数)
输出:
结果。四舍五入到小数点后第二位的浮点数。
我的代码是:
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个例子inputs/outputs:
示例输入:
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个测试。
提前致谢。
P.S。难不成是任务条件出错了?
首先你的问题问的是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'
我有以下任务:
乔治今晚要请客,他决定买鲣鱼、竹荚鱼和贻贝。他去鱼市买了几公斤。您在控制台中以美元输入鲭鱼和西鲱的价格。您还可以输入以千克为单位的鲣鱼、竹荚鱼和贻贝的数量。如果鱼市的价格是:
,乔治需要多少钱来买单?- 鲣鱼 - 比鲭鱼贵 60%
- 竹荚鱼 - 比西鲱贵 80%
- 贻贝 - 7.50 USD/kg
输入:
- 第一行:鲭鱼价格(浮点数)
- 第二行:西鲱价格(浮点数)
- 第三行:鲣鱼的数量(浮点数)
- 第四行:竹荚鱼的数量(公斤)
- 第五行:以公斤为单位的贻贝数量(整数)
输出: 结果。四舍五入到小数点后第二位的浮点数。
我的代码是:
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个例子inputs/outputs:
示例输入:
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个测试。
提前致谢。
P.S。难不成是任务条件出错了?
首先你的问题问的是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'