Что не так с моим среднеквадратичным средним? - PullRequest
0 голосов
/ 15 сентября 2018

Я работал над этим кодом, который вычисляет среднеквадратичное значение комнаты.Кажется, что-то не так с моей структурой цикла, может кто-нибудь помочь найти мою ошибку?спасибо!

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 голосов
/ 15 сентября 2018

Не важно, я вижу, что вы хотели все это в 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()
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 rms.py 
This program will calculate the RMS of your values.

Please enter the number of values you want calculated: 3
Enter a desired values:10
Enter a desired values:3
Enter a desired values:2

The Root Mean Square is: 1.4501197686295146
0 голосов
/ 15 сентября 2018

Вы ошиблись, что там total = total + math.sqrt(x) неправильно, что вы должны найти квадрат x Not квадратный корень из 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))
0 голосов
/ 15 сентября 2018

Если я правильно сделаю вывод, вы хотите взять каждый вход, возвести его в квадрат, усреднить сумму и получить квадратный корень из этой суммы. Помните, что при усреднении (нахождении среднего) делите только на сумму в конце:

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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...