【问题标题】:Write a function called findHypot编写一个名为 findHypot 的函数
【发布时间】:2020-02-04 20:48:38
【问题描述】:

我的任务:编写一个名为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>

【问题讨论】:

  • 您需要指定您要询问的内容。请注意,尽管 ((a*a)+(b*b)%2) 没有做任何事情,因为您不会将结果存储在任何地方,但我认为您不希望在那里取模 (%),并且您永远不会调用该函数。
  • 另外,您正在打印对函数 findhypot 的引用,而不是调用它并打印返回值。它应该是findhypot(a,b)
  • @teukkam 该评论可能是答案的基础......

标签: python


【解决方案1】:

您的代码存在一些问题,但让我们先看看输出。你得到了那个输出,因为你没有调用你定义的函数:

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(...)

【讨论】:

  • 太棒了...我现在明白了
  • 太棒了...我现在明白了