gpt4 book ai didi

python - Python中如何四舍五入到最接近的小数

转载 作者:行者123 更新时间:2023-12-01 00:45:30 25 4
gpt4 key购买 nike

这是我第一次使用 Python。我正在尝试找出如何以最简单的方式四舍五入小数。

print("\nTip Calculator")

costMeal = float(input("Cost of Meal:"))

tipPrct = .20
print("Tip Percent: 20%")

tip = costMeal * tipPrct

print("Tip Amount: " + str(tip))

total = costMeal + tip
print("Total Amount: " + str(total))

I need it to look like this image.

最佳答案

您应该使用Python's built-in round function.

round() 语法:

round(number, number of digits)

round()的参数:

..1) number - number to be rounded
..2) number of digits (Optional) - number of digits
up to which the given number is to be rounded.
If not provided, will round to integer.

因此,您应该尝试类似的代码:

print("\nTip Calculator")

costMeal = float(input("Cost of Meal: "))

tipPrct = .20
print("Tip Percent: 20%")

tip = costMeal * tipPrct
tip = round(tip, 2) ## new line

print("Tip Amount: " + str(tip))

total = costMeal + tip
print("Total Amount: " + str(total))

关于python - Python中如何四舍五入到最接近的小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57011481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com