#e9.1Calstatistics.py from math import sqrt def getNum(): #获取用户输入 nums = [] iNumStr = input("请输入数字(直接输入回车退出):") while iNumStr!="": nums.append(eval(iNumStr))iNumStr=input("请输入数字(直接输入回车退出):") return nums def mean(numbers): #计算平均值 s=0.0 for num in numbers: s=s+num return s/len(numbers) def dev(numbers, mean):#计算方差 sdev=0.0 for num in numbers: sdev= sdev+ (num - mean)**2 return sqrt(sdev/(len(numbers)-1)) def median(numbers): #计算中位数 sorted(numbers) size=len(numbers) if size 82==0: med=(numbers[size//2-1]+numbers[size//2])/2 else: med=numbers[size//2] return med n=getNum() #主体函数 m=mean(n) print("平均值:{},方差:{:.2},中位数:{}.".format(m,\ dev(n,m),median(n)))用python在以上代码中增加函数,实现最大值、最小值的计算和输出,不用python内置函数max,min
时间: 2024-02-20 16:58:16 浏览: 74
可以在以上代码中增加如下函数来实现最大值、最小值的计算和输出:
```python
def max_min(numbers):
max_num = numbers[0]
min_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
if num < min_num:
min_num = num
return max_num, min_num
```
然后在主体函数中调用该函数并输出结果:
```python
n = getNum() # 获取用户输入
m = mean(n)
max_num, min_num = max_min(n)
print("平均值:{}, 方差:{:.2}, 中位数:{}, 最大值:{}, 最小值:{}.".format(m, dev(n, m), median(n), max_num, min_num))
```
阅读全文