python - 使用不同的循环结构时会有不同的答案

标签 python for-loop while-loop

我必须创建以下代码来确定一个人在一定时间内接触到的辐射量。我用 for 循环创建了它,我的答案是 75% 正确,我检查了 friend 使用 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

关于python - 使用不同的循环结构时会有不同的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28277983/

相关文章:

python pandas 无法显示大数据框的摘要

javascript - v-for 在 v-if 条件下,v-else 不起作用,循环重复

python解析文件并放入for循环

javascript - 循环浏览页面直到找到特定电影

python随机洗牌while循环

python - 如何在 Windows 上为 python 安装 igraph

安装了Python3.5但pip3指向python3.6

python matplotlib 绘制稀疏矩阵模式

java - GC 和在 for 循环中赋值

python - 如何减少语句中的条件数量?