import random def calculate_mean(data): return sum(data) / len(data) def calculate_median(data): sorted_data = sorted(data) n = len(sorted_data) if n % 2 == 0: return (sorted_data[n//2 - 1] + sorted_data[n//2]) / 2 else: return sorted_data[n//2] def calculate_variance(data): mean = calculate_mean(data) return sum((x - mean) ** 2 for x in data) / len(data) def calculate_standard_deviation(data): variance = calculate_variance(data) return variance ** 0.5 class Cal: # 创建一个人类 """定义计算类""" def __init__(self, data): # 构造方法 self.data=data def run(self): # 定义跑的方法 print(self.eye) def calculate_mean(self): temp=sum(self.data) / len(self.data) return sum(self.data) / len(self.data) def calculate_median(self): sorted_data = sorted(self.data) n = len(sorted_data) if n % 2 == 0: return (sorted_data[n//2 - 1] + sorted_data[n//2]) / 2 else: return sorted_data[n//2] def calculate_variance(self): mean = calculate_mean(self.data) return sum((x - mean) ** 2 for x in self.data) / len(self.data) def calculate_standard_deviation(self): variance = calculate_variance(self.data) return variance ** 0.5 def main(): source = input("请选择数据来源: 1.系统自动生成随机数;2.键盘输入一组数据 ") if source == '1': data = [random.randint(1, 100) for _ in range(11)] elif source == '2': data = [] while True: try: num = input("请输入数字(直接输入回车退出): ") if num == '': break data.append(float(num)) except ValueError: print("请输入有效数字!") else: print("输入错误!") if data: cal1 = Cal(data) # 创建人类的实例 mean = calculate_mean(data) median = calculate_median(data) std_dev = calculate_standard_deviation(data) print(f"序列为: {data}, 平均值: {mean:.2f}, 标准差: {std_dev:.2f}, 中位数: {median:.2f}") print(f"序列为: {data}, 平均值: {cal1.calculate_mean():.2f}, 标准差: {cal1.calculate_standard_deviation():.2f}, 中位数: {cal1.calculate_median():.2f}") #cal1.calculate_mean() if __name__ == "__main__": main()