[英]Python Sum of digits with average
Hello everyone i am a new to programming and i have a small problem in the code, i need to get the average of the sum i already made the sum of digits and here is the code:大家好,我是编程新手,代码中有一个小问题,我需要求出总和的平均值,我已经对数字求和了,这里是代码:
num = int(input("Enter a number\n"))
r = 0
m = 0
while num != 0:
m = num % 10
r = r + m
num = int(num / 10)
print(f"The sum of all digits is {result} and the average is")
i need the average but i dont know how to get it( for example in the num i added 5555, 5+5+5+5 = 20) how would i get the average and thanks我需要平均值,但我不知道如何得到它(例如在我添加 5555、5+5+5+5 = 20 的数字中)我如何得到平均值,谢谢
i tried to do r / m but also didnt work我试着做 r / m 但也没有用
This is the short solution:这是简短的解决方案:
num = input("Enter a number\n")
s = sum([int(x) for x in num])
a = s / len(num)
print(f"The sum of all digits is {s} and the average is {a}")
Also, this is the fixed version of your code:此外,这是您的代码的固定版本:
num = int(input("Enter a number\n"))
r = 0
m = 0
t = 0
while num != 0:
m = num % 10
r = r + m
num = int(num / 10)
t = t + 1
print(f"The sum of all digits is {r} and the average is {r/t}")
n_str = input("Enter numbers by gaps: ") n = [float(num) for num in n_str.split()] summ = 0 for i in n: summ = summ + i print("Average of ", n, " is ", summ / len(n))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.