学习编程这件事,很想很想,却一直不知道如何开始。更准确地说,不敢于去尝试开始。昨天,听完老师的课,终于自己动手写了一页比较长的代码,而且得到了老师的认可,好开心!老师给的练习题是求解一个列表的最小值、最大值、元素数和平均值:
Your task is to process a sequence of integer numbers to determine the following statistic:
- minimum value
- maximum value
- number of elements in the sequence
- average value
For example:[6,9,15,-2,92,11]
正确的输出结果是这样的:
- minimum value = -2
- maximum value = 92
- number of elements in the sequence = 6
- average value = 21.833333
但自己输出的平均值只能是21.0或者21,后面的几位小数出不来。请教了老师,说是和后面马上要学的数据类型有关系。按老师的方法乘了一个1.0,就得到了正确的结果。自己的代码如下:
def MinResult(grades):
n=0
MinValue=grades[1]
while n < len(grades):
if grades[n]<MinValue:
MinValue=grades[n]
n=n+1
return MinValue
def PrintMinResult(grades):
print (MinResult(grades))
def MaxResult(grades):
n=0
MaxValue=grades[1]
while n < len(grades):
if grades[n]>MaxValue:
MaxValue=grades[n]
n=n+1
return MaxValue
def PrintMaxResult(grades):
print (MaxResult(grades))
def PrintNumberOfElements(grades):
print(len(grades))
def AverageValue(grades):
n=0
sum=0
while n<len(grades):
sum=sum+grades[n]
n=n+1
AverageResult=1.0*sum/len(grades)
return round(AverageResult,6)
def PrintAverageValue(grades):
print(AverageValue(grades))
grades_A=[6,9,15,-2,92,11]
PrintMinResult(grades_A)
PrintMaxResult(grades_A)
PrintNumberOfElements(grades_A)
PrintAverageValue(grades_A)
小确幸。