문제

나는 현재 피타고라스 정리를 해결할 프로그램을 작성하고 있습니다. 그러나 프로그램에 버그가 있습니다. 길이 a 또는 b에 대해 음수를 넣을 때마다 "a는 0보다 작을 수 없다"고 인쇄하지만 계속해서 C를 해결하고 사용자가 아직 B를 입력하지 않더라도 C의 길이를 인쇄합니다. 사용자가 음수를 입력하면 "A a가 0보다 작을 수 없다"라는 문자를 인쇄 한 다음 다시 반복하여 측면의 길이를 입력하여 다시 루프가 된 후에는 어떻게 인쇄 된 후에는 어떻게 인쇄하는지 대신 다시 고정시킬 수 있도록하는 방법은 어떻게 만들 수 있습니까? 진술은 끝까지 리디렉션합니까?

내 코드는 다음과 같습니다.

 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 + "."
도움이 되었습니까?

해결책 2

우선 입력을 지속적으로 확인하려면 루프를 사용해야합니다. 에서와 마찬가지로 알고리즘의 psuedocode는 다음과 같습니다.

Loop Begin
Check the value of a and b
If a or b is less than 0 then ask for input again
Otherwise, continue

알고리즘에 유의하십시오 가지다 실행하려면 적어도 한 번.

그것이 기본적으로 psuedocode의 방법입니다 ~해야 한다 보입니다. 그래서 이것은 당신이 사용할 수있는 경우입니다. do-while 루프 구성. 파이썬에는 이와 같은 것이 없으므로 우리는 에뮬레이션 그것:

import math


def take_in():
    a = raw_input("Enter the value of side a -> ")
    b = raw_input("Enter the value of side b -> ")

    # Trying to convert to a float
    try:
        a, b = float(a), float(b)
        # If successfully converted, then we return
        if a > 0 and b > 0:
            return a, b
    except ValueError:
        pass
    # If we cannot return, then we return false, with a nice comment

    print "Invalid input"
    return False


def main():
    # Calling the function at least once
    valid = take_in()

    # While we are not getting valid input, we keep calling the function
    while not valid:
        # Assigning the value to valid
        valid = take_in()

    # Breaking the return tuple into a and b
    a, b = valid
    print math.sqrt(a ** 2 + b ** 2)


if __name__ == '__main__':
    main()

다른 팁

당신은 하나의 인두 타티노 레벨을 놓쳤습니다. 다음과 같이 시도하십시오.

if a<0:
  print"A cannot be less than zero"
else:
    b=raw_input('Enter the length of side b')
    b=float(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 + "."

중첩을 사용하지 마십시오 if 프로그램이 설계 할 때. 그것은 이런 종류의 버그로 이어집니다 (한 수준의 들여 쓰기). 내부의 큰 코드 덩어리 if 블록과 많은 중첩 if 블록은 프로그램을 따르기가 더 어려워지고 이유가 있습니다.

대신 입력이 유효 할 때까지 다시 물어볼 수 있습니다.

a = -1
while a < 0:
    try:
        a=float(raw_input('Enter the length of side a'))
    except ValueError:
        pass
    if a<0:
        print "A cannot be less than zero"

프레드의 조언은 좋습니다. 재사용 기능으로 마무리하십시오.

def validate(initial, prompt, test, message, typecast=str):
    value = initial
    while not test(value):
        try:
            value = typecast(raw_input(prompt))
        except ValueError:
            print "Invalid value"
            continue

        if not test(value):
            print message
            continue

        return value

그런 다음 사용하십시오 :

a = validate(
    initial = -1, 
    prompt = 'Enter the length of side A', 
    test = lambda x: x >= 0,
    message = "A cannot be less than zero",
    typecast = float
)
b = validate(
    initial = -1, 
    prompt = 'Enter the length of side B', 
    test = lambda x: x >= 0,
    message = "B cannot be less than zero",
    typecast = float,
)

면책 조항 : 다른 버전의 파이썬을 사용하고 있으므로 마일리지가 다를 수 있습니다.

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를 요구하는 진술을 각각 반복합니다 (일반적인 의미에서 유효합니다. 오류 확인이 없습니다. 문자열을 사용하면 어떻게됩니까 ??>. <) 이제 인쇄물이 약간 펑키합니다. 나는 분명히 파이썬 문서를 조사하고 %d %s 등이 무엇인지 알 수 있습니다. 그런 다음 메소드의 반환 (def py_theorem 위로 위 참조)을 유닛과 함께 문자열로 전달합니다. 이 함수는 각각 두 개의 인수 A, B를 취합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top