for循环格式
def average(*args): sum = 0.0 if len (args) == 0: return sum for x in args: sum = sum + x average = sum *1.0 /len (args) return average print average() print average(1, 2) print average(1, 2, 2, 3, 4) 这样写为什么不会输出正确答案啊
def average(*args): sum = 0.0 if len (args) == 0: return sum for x in args: sum = sum + x average = sum *1.0 /len (args) return average print average() print average(1, 2) print average(1, 2, 2, 3, 4) 这样写为什么不会输出正确答案啊
2019-06-11
你的格式是不是这样呀 for x in args: sum = sum + x average = sum *1.0 /len (args) return average 如果是的话,sum值只加了第一个元素,average又除以了总的参数个数,所以输出的答案就是错误的 只要把sum和average放在for循环外面就可以了,具体可以见下面的代码 def average(*args): sum = 0.0 if len (args) == 0: return sum else: for x in args: sum = sum + x average = sum *1.0 /len (args) return average print average() print average(1, 2) print average(1, 2, 2, 3, 4)
举报