问题描述
我一直在研究计算房间均方值的代码。 我的循环结构似乎出了点问题,有人可以帮助找到我的错误吗? 谢谢!
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))
1楼
没关系,我从阅读中看到您想要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
2楼
您犯了一个错误,其中存在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))
3楼
如果我正确地推断出,那么您想将每个输入取平方,求和并求平均值,然后求和。 请记住,求平均时(寻找均值),仅需除以最后的和:
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)