我的均方根平均值有什么问题?

时间:2018-09-15 18:28:51

标签: python loops

我一直在研究计算房间均方值的代码。我的循环结构似乎出了点问题,有人可以帮助找到我的错误吗?谢谢!

def rms():
    print("This program will calculate the RMS of your values.")
    print()
    n = int(input("Please enter the number of values you want 
    calculated: "))
    total = 0.0
for i in range(n):
    x = float(input("Enter a desired values:"))
    total = total + math.sqrt(x)



print("\nThe Root Mean Square is:", math.sqrt(total/n))

3 个答案:

答案 0 :(得分:0)

没关系,我从阅读中看到您想要thisMethod中的所有内容,但我相信您希望rms()中的所有内容都应谨慎处理缩进,以使函数的某些部分不会超出功能范围,尽管可以,但不能确定所需的输出。

rms()
import math

def rms():
    print("This program will calculate the RMS of your values.")
    print()
    n = int(input("Please enter the number of values you want calculated: "))
    total = 0.0 
    for i in range(n):
        x = float(input("Enter a desired values:"))
        total = total + math.sqrt(x)
    print("\nThe Root Mean Square is:", math.sqrt(total/n))

rms()

答案 1 :(得分:0)

您犯了一个错误total = total + math.sqrt(x),错误是您应该找到平方x 而不是 x平方根,因此请尝试我的固定代码:-

def rms():
    print("This program will calculate the RMS of your values.\n")
    n = int(input("Please enter the number of values you want calculated: "))
    total = 0.0
    for i in range(n):
        x = float(input("Enter a desired values:"))
        total += x ** 2 #it means x powered by two

    print("\nThe Root Mean Square is:", math.sqrt(total/n))

答案 2 :(得分:-1)

如果我正确地推断出,那么您想获取每个输入,对其求平方,求和并求和并求平方根。请记住,求平均时(寻找均值),只能除以最后的总和:

def rms():
    total = 0.0
    count = 0
    while True:
        x = input('enter value (enter nothing to stop):')
        if x.strip() == '':
            break
        count += 1
        total += float(x) ** 2

    print('mean square root is:', math.sqrt(total/count))
    # return math.sqrt(total / count)