Python无法返回最终值

2024-06-01 21:19:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直坚持这个任务。 我试图用我的代码进行不同的组合以获得返回值,但失败了。 问题是用递归法求出一段时间内的辐射暴露量。在

问题:我可以正确地得到所有的计算结果[我使用在线python executor检查了它],但是当进程到达最后的返回时,结果是None。我不知道为什么我的代码不能返回最终的计算结果。我希望:外面的大师能给我一些线索谢谢。在

global totalExposure
totalExposure=0 

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

def radiationExposure(start, stop, step):
    time=(stop-start)
    newStart=start+step

    if(time!=0):
        radiationExposure(newStart, stop, step) 
        global totalExposure
        totalExposure+=radiation   
        radiation=f(start)*step
    else:
        return totalExposure

测试用例1:

^{pr2}$

Tags: 代码returntimedefstepmathglobalstart
3条回答

似乎您忘记了if子句中的return。在else中有一个,但在if.中没有

正如其他人提到的,你的if语句没有返回。你好像忘了if子句中的返回。其他地方有一个,但是如果没有。在

正如保罗提到的,你的if语句没有返回。另外,在分配变量radiation之前,您正在引用它。一些调整,我可以让它工作。在

global totalExposure
totalExposure = 0 

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

def radiationExposure(start, stop, step):

    time = (stop-start)
    newStart = start+step

    if(time!=0):
        radiationExposure(newStart, stop, step) 
        global totalExposure
        radiation = f(start) * step
        totalExposure += radiation
        return totalExposure
    else:
        return totalExposure

rad = radiationExposure(0, 5, 1)
# rad = 39.1031878433

相关问题 更多 >