编写程序,实现总个数、求和、平均值、方差、中位数等基本统计值的计算。
时间: 2024-10-16 22:03:49 浏览: 90
统计与数据分析基础-04描述性统计分析.pptx
编写一个简单的程序,用于计算一组数字的基本统计值,可以按照以下步骤进行:
1. **数据输入**:首先,需要用户输入一组数值,通常存储在一个列表或数组中。
```python
numbers = list(map(int, input("请输入一串数字,用空格分隔:").split()))
```
2. **函数定义**:创建函数分别计算总个数、求和、平均值、方差和中位数。
```python
def count_numbers(numbers):
return len(numbers)
def sum_of_numbers(numbers):
return sum(numbers)
def average(numbers):
return sum_of_numbers(numbers) / count_numbers(numbers)
def variance(numbers):
avg = average(numbers)
return sum((x - avg) ** 2 for x in numbers) / count_numbers(numbers)
def median(numbers):
numbers.sort()
length = count_numbers(numbers)
if length % 2 == 0:
return (numbers[length // 2] + numbers[length // 2 - 1]) / 2
else:
return numbers[length // 2]
```
3. **计算并输出结果**:将每个函数的结果打印出来。
```python
total_count = count_numbers(numbers)
sum_value = sum_of_numbers(numbers)
avg = average(numbers)
variance_result = variance(numbers)
median_result = median(numbers)
print(f"总个数:{total_count}")
print(f"求和:{sum_value}")
print(f"平均值:{avg}")
print(f"方差:{variance_result}")
print(f"中位数:{median_result}")
```
阅读全文