使用不同的循环结构时的不同答案

different answers when using different loop constructs

我必须创建以下代码来确定一个人在特定时间内受到的辐射量。我用 for 循环创建了它,我的答案是 75% 正确,我检查了一个使用 while 循环的朋友的代码,他 100% 正确所以,我的问题是为什么或什么是这两个代码之间的区别还是我在 For 循环中没有做什么?

我用这些行调用了函数

radiationExposure(0, 11, 1)
radiationExposure(40, 100, 1.5)

这是代码:

def f(x):
    import math
    return 10*math.e**(math.log(0.5)/5.27 * x)

def radiationExposure(start, stop, step):
    cuenta = 0.0
    Iter = stop - start

    for i in range(start,(Iter)+start):
        temp = f(i) * step
        cuenta += temp
    return cuenta

其他代码(正确):

def f(x):
    import math
    return 10*math.e**(math.log(0.5)/5.27 * x)

def radiationExposure(start, stop, step):      
    result = 0
    while start < stop:
        result += f(start) * step
        start += step
    return result

您正在忽略范围内的 step 参数。 while 循环通过将 step 添加到 start 来递增,但您仅递增 1。

您可以在 for 循环中包含 step 值:

for i in range(start, stop, step):

请注意,我删除了 Iter 变量;你不需要它,它是多余的。只需使用 stop 作为 range() 对象的结束值。

现在 i 将设置为 startstart + 1 * stepstart + 2 * step 等,而不是 startstart + 1start + 2,等等

您这样做可能是因为range() 不支持浮点值。您不能使用 1.5,因此要正确解决此问题,您 必须 使用不同类型的循环。

如果你真的想,你仍然可以使用 range():

length = int(1 + (stop - 1 - start) / step)
for counter in range(length):
    i = start + counter * step
    temp = f(i) * step
    cuenta += temp

这会首先计算您的循环总共需要执行多少步,然后再循环多少次。每次迭代都会根据循环计数器计算该迭代的实际值。

我会说使用 while 循环更容易。

至少有了这个改变,两种方法的结果是一样的:

>>> import math
>>> def f(x):
...     return 10*math.e**(math.log(0.5)/5.27 * x)
... 
>>> def radiationExposure_while(start, stop, step):
...     result = 0
...     while start < stop:
...         result += f(start) * step
...         start += step
...     return result
... 
>>> def radiationExposure_range(start, stop, step):
...     result = 0
...     length = int(1 + (stop - 1 - start) / step)
...     for counter in range(length):
...         i = start + counter * step
...         result += f(i) * step
...     return result
... 
>>> radiationExposure_range(0, 11, 1) == radiationExposure_while(0, 11, 1)
True
>>> radiationExposure_range(40, 100, 1.5) == radiationExposure_while(40, 100, 1.5)
True

您的 for 循环步进 1 并忽略 step 参数

for i in range(start, (Iter)+start)

为了说明步骤,将最后一个参数添加到 range

for i in range(start, (Iter)+start, step)