我正在试图找出我的代码有什么问题。任何人都可以解决它吗?
def main():
fname = input("Enter filename:")
infile = open(fname, "r")
SD()
def SD():
b= []
a = 5.0
r = len(b)
for n in range(r-1):
b.append((r[n] -a)**2)
m = (float(b)/r)**0.5
print("The standard deviation is", m)
main()
答案 0 :(得分:5)
你有一些错误:
def SD():
# b is empty
b= []
a = 5.0
#this will always be 0
r = len(b)
# range(r-1) == [] because it is range(-1)
# whole loop is skipped
for n in range(r-1):
b.append((r[n] -a)**2)
# float(b) should throw an error, maybe sum(b) ?
m = (float(b)/r)**0.5
print("The standard deviation is", m)
main()
b
是一个列表;你不能把一个列表放到浮点数中。
也许您想将数组传递给SD()
?你应该read()
文件内容然后split()
进入数组并将其作为参数传递给SD()(你将在其上调用int()
。)
答案 1 :(得分:1)
样本:
def SD(numList):
cntN=len(numList)
sumN=0
for i in numList:
sumN+=i
avgVal=float(sumN)/float(cntN)
sumVar=0.0
for i in range(cntN):
sumVar+=float((numList[i]-avgVal)**2)
return ((float(sumVar)/float((cntN-1)))**0.5)