【发布时间】:2017-03-22 04:12:40
【问题描述】:
我正在尝试编写一个使用矩形规则计算积分的代码,并且还允许用户输入积分限制和除数(矩形)的数量。我已经编写了该函数,但对于某些值,它只返回“无”。知道为什么吗?
到目前为止,这是我的代码:
def integral(f, a, b, N):
h = int((b-a)/N)
result = 0
result += h * f(a)
for i in range(1, N-1):
result += h * f(a + i*h)
return result
def f(x):
return x**3
string_input1 = input("Please enter value for a: ")
a = int(string_input1)
string_input2 = input("Please enter value for b: ")
b = int(string_input2)
while True:
string_input3 = input("Please enter integer positive value for N: ")
N = int(string_input3)
if N>0:
break
print(integral(f, a, b, N))
返回“无”的值的示例是 a=0 b=1 N=2
【问题讨论】:
-
h是int? -
@WillemVanOnsem 你确定
return result的缩进吗?如果N=2,它可能会解释None。 -
@DeepSpace:这个程序一开始就不是故意的。我有修复它的想法,但我不能确定。根据旧的缩进,它在循环中,但谁能确定呢?
-
@Eve:
return语句是 inside 还是 outsidefor循环? -
@WillemVanOnsem 返回应该在 for 循环之外,我试过了,现在我得到 0 而不是仍然不正确的 None
标签: python numerical-integration