编写一个名为findHyp的函数

2024-10-03 19:20:10 发布

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

我的任务是:编写一个名为findhypot的函数。函数将给定直角三角形两边的长度,并返回斜边的长度

我想出了以下解决办法:

def findhypot(a , b):
    ((a*a)+(b*b)%2)
    return a , b

a = int(input("Pls lenter length of Opposite: "))
b = int(input("Pls enter the length of Adjascent: "))

print("The lenght of the hypotenous is",findhypot)

但我得到的不是正确的值,而是以下输出:

The lenght of the hypotenous is <function findhypot at 0xgibberish>

Tags: ofthe函数inputreturnisdeflength
1条回答
网友
1楼 · 发布于 2024-10-03 19:20:10

您的代码有一些问题,但是让我们先看看输出。您将获得该输出,因为您没有调用您定义的函数:

print("The lenght of the hypotenous is",findhypot)

因此,您不应该将findhypot放在print中,而应该调用它并通过input传递刚刚收到的两个参数:

print("The lenght of the hypotenous is",findhypot(a,b))

但这会给你(假设你的输入是3和4):

The lenght of the hypotenous is (3, 4)

为什么?因为您只是在函数中返回a和b,没有进一步的计算:

return a , b

没有进一步的计算?但是有一条线在用a,b做什么!是的,但该计算值从未赋值或返回,因此请使用变量获取计算结果:

def findhypot(a , b):
    result = ((a*a)+(b*b)%2)
    return result

或者直接返回计算结果:

def findhypot(a , b):
    return ((a*a)+(b*b)%2)

但现在你将得到9作为3和4的结果。5应该是正确的值。我把那个问题的解决办法留给你了。提示:毕达哥拉斯,import mathmath.sqrt(...)

相关问题 更多 >