检测三个数字是否能构成直角三角形的程序

0 投票
3 回答
871 浏览
提问于 2025-04-18 01:47

这是我目前写的程序:

def main4():
    if isRight():
        print('it is right')
    if not isRight():
        print('it is not right')
def isRight():
    n1=int(input('Enter first number:'))
    n2=int(input('Enter second number:'))
    n3=int(input('Enter third number:'))
    if n1<n2 and n1<n3:
        smallest=n1
    elif (n1<n2 and n1>n3) or (n1<n3 and n1>n2):
        smaller=n1
    elif n2<n1 and n2<n3:
        smallest=n2
    elif (n2<n1 and n2>n3) or (n2<n3 and n2>n1):
        smaller=n2
    elif n3<n2 and n3<n1:
        smallest=n3
    elif (n3<n2 and n3>n1) or (n3<n1 and n3>n2):
        smaller=n3
    elif n1>n2 and n1>n3:
        largest=n1
    elif n2>n1 and n2>n3:
        largest=n2
    else:
        largest=n3
    if largest**2==(smallest**2)+(smaller**2):
        return true
    else:
        return false

当我调用主函数时,它让我输入三个数字,但随后却返回了这个错误信息:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    main4()
  File "/Users/L/Documents/maxoftwo.py", line 45, in main4
    if isRight():
  File "/Users/L/Documents/maxoftwo.py", line 71, in isRight
    if largest**2==(smallest**2)+(smaller**2):
UnboundLocalError: local variable 'largest' referenced before assignment

我不知道该怎么解决这个错误,如果有人能帮帮我,我会非常感激。谢谢你们!

3 个回答

0

你的条件只设置了一个变量。你需要把你那长长的 if/elif 语句拆分成三部分,每部分分别设置一个 smallestsmallerlargest 变量。

0

在你使用本地变量 largest 之前,你需要给它赋一个值。

def main4():
    result = isRight()

    if result:
        print('it is right')
    else:
        print('it is not right')

def isRight():
    largest = 0              # <-
    smallest = 0             # <-
    smaller = 0              # <-
    ...

    # calculate each other
    if largest**2==(smallest**2)+(smaller**2):
        ...
1

你的代码结构是这样的:它会进入你设置的9个条件块中的一个,来计算smallersmallestlargest这三个值。当它从某个条件块出来时,只有这三个变量中的一个会被声明。所以当代码执行到这段

if largest**2==(smallest**2)+(smaller**2):

时,只能找到这三个变量中的一个,因此就会出现你看到的错误。要解决这个问题,你可以在获取用户输入后,声明这三个变量:

smallest=largest=smaller=0

在你询问用户输入变量之后,这样你的程序就能正常运行了。

你的代码还有一些其他问题:

  • TrueFalse是Python中定义好的关键字,而truefalse则不是。所以一定要使用大写的单词。
  • main4这个函数中,第二个if可以用else来替代。在你现在的代码中,isRight这个函数会被调用两次,这其实是不必要的。
  • 你可以简化计算smallersmallestlargest这三个变量的条件,变成:

    smallest = min(n1, n2, n3)
    largest = max(n1, n2, n3)
    smaller = list(set([n1, n2, n3]) - set([smallest, largest]))[0]
    

撰写回答