python编写程序,输入4个数,求出它们的平均数并输出,要求保留小数点后2位。(输出时用3种方式实现保留小数点后两位操作)
时间: 2024-10-29 18:21:09 浏览: 3
python输入一个水仙花数(三位数) 输出百位十位个位实例
在Python中,计算四个数的平均值并保留小数点后两位有多种方法。以下是三种常见的实现方式:
1. 使用`round()`函数直接处理:
```python
def average(numbers):
total = sum(numbers)
avg = round(total / len(numbers), 2)
print("Average (using round):", avg)
numbers = [float(input(f"请输入第{i+1}个数: ")) for i in range(4)]
average(numbers)
```
2. 利用f-string格式化输出:
```python
def average(numbers):
total = sum(numbers)
avg = total / len(numbers)
print(f"Average (format string): {avg:.2f}")
numbers = [float(input(f"请输入第{i+1}个数: ")) for i in range(4)]
average(numbers)
```
3. 使用`decimal`模块处理高精度浮点数:
```python
from decimal import Decimal
def average(numbers):
total = sum(Decimal(num) for num in numbers)
avg = total / Decimal(len(numbers))
print("Average (decimal module): {:.2f}".format(avg))
numbers = [float(input(f"请输入第{i+1}个数: ")) for i in range(4)]
average(numbers)
```
阅读全文