我目前正在编写一个程序来解决毕达哥拉斯定理。然而,我在程序中有一个bug。每当我输入一个长度为a或b的负数时,它就会打印出"A不能小于零“,然后继续对C进行求解,并打印出C的长度,即使用户还没有输入b。如果用户输入一个负数,它就会打印出语句"A不能小于零“,然后再循环输入边的长度,而不是在打印出重定向到末尾的语句之后,它现在的位置如何?
这是我的代码:
 import math
    print"This program will solve the pythagorean theorem for you"
    unit=raw_input('Enter the unit you will be using')
    a=float(raw_input('Enter the length of side a'))
    if a<=0:
      print"A cannot be less than zero"
    else:
        b=float(raw_input('Enter the length of side b'))
    if b<=0:
      print"B cannot be less than zero"
    else:
        c2=(a**2)+(b**2)
        c=math.sqrt(c2)
        c=str(c)
        print "The length of side C is: "+ c + " " + unit + "."发布于 2013-11-07 17:48:58
免责声明:我使用的是Python的不同版本,所以里程数可能会有所不同
import math
a = 0
b = 0
def py_theorem(a, b):
    return(a**2 + b**2)
unit = raw_input('Enter the unit you will be using: ')
while a <= 0:
a = float(raw_input('Enter the length of side A: '))
if a <= 0:
    print('A cannot be less than 0.')
while b <= 0:
b = float(raw_input('Enter the length of side B: '))
if b <= 0:
    print('B cannot be less than 0.')
print('The length of the 3rd side C is %d %s') % (py_theorem(a,b), unit)现在,如果您看我的代码a,b最初是0,这样您就可以执行while循环(否则您会得到一个错误,解释器直到那时还不知道a,b)。然后重复分别要求a、b的语句,直到得到有效的输入(在一般意义上是有效的,我们没有错误检查,如果使用字符串怎么办??>.<),现在打印有点古怪,我肯定会查看Python,看看%d %s等等是什么。然后,我们将方法的返回(见顶部的def py_theorem )与一个单元一起传递给字符串。注意,该函数分别采用两个参数a、b。
https://stackoverflow.com/questions/19842500
复制相似问题