[英]What is wrong with my root mean square average?
我一直在研究計算房間均方值的代碼。 我的循環結構似乎出了點問題,有人可以幫助找到我的錯誤嗎? 謝謝!
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()
所有內容,我相信您希望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
您犯了一個錯誤,其中存在total = total + math.sqrt(x)
錯誤是您應該找到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))
如果我正確地推斷出,那么您想將每個輸入取平方,求和並求平均值,然后求和。 請記住,求平均時(尋找均值),僅需除以最后的和:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.