Python Book의 '숙제'질문 : 주어진 방정식을 사용하여 사용자에게 삼각형 각도의 3 점을 입력하고 그 면적을 표시하도록하는 프로그램을 작성하십시오.
s = (side1 + side2 + side3) / 2
area = √s(s - side1)(s - side2)(s - side3)
내가 실행했을 때 작성한 프로그램은 오류를 표시하는데 근본 원인과 해결 방법을 이해할 수 없습니다.
#Calculate the area of a triangle
# Enter coordinates for 3 points
sideOne = 1.5, -3.4#(x1, y1) = eval(input("Enter coords for side1:"))
sideTwo = 4.6, 5#(x2, y2) = #eval(input("Enter coords for side2:"))
sideThree = 9.5, -3.4#(x3, y3) = #eval(input("Enter coords for side3:"))
# Calculate s value
sideAll = (sideOne + sideTwo + sideThree) / 2# Compute Area
area = (sideAll(sideAll - sideOne)(sideAll - sideTwo)(sideAll - sideThree)) * * 0.5# Display Area
print("The Area of entered Triangle:", area)
결과 오류
Traceback(most recent call last):
File "J:\Programming\PROGRAMMING\Python\Exercises\Chapter 2\Programming Exercises - 2.14 Skip.py", line 8, in < module >
sideAll = (sideOne + sideTwo + sideThree) / 2
TypeError: unsupported operand type(s) for / : 'tuple'
and 'int'
당신이 할 때 sideOne = 1.5, -3.4
, 다음 sideOne
A는 튜플 .
따라서 기본적으로 (귀하의 의견에서 말했듯이) (x,y)
, here 형식의 3 점 중 하나의 좌표입니다 (1.5, -3.4)
.
튜플에서 직접 산술 연산을 할 수는 없습니다. 튜플은 데이터를 표현하는 방법 일 뿐이고 파이썬은 그것이 좌표라고 추측하지 않기 때문에 이렇게하는 것은 의미가 없습니다.
대신 숫자 값 (정수, 부동 소수점 등)에 대해 수학적 연산을 수행 할 수 있지만 튜플에서는 수행 할 수 없습니다.
대신 변의 길이 를 계산 한 다음 공식에 지정된대로 사용할 수 있습니다.
다음과 같이 시도해 볼 수 있습니다.
import math
#Calculate the area of a triangle
# Enter coordinates for 3 points
a = 1.5, -3.4#(x1, y1) = eval(input("Enter coords for side1:"))
b = 4.6, 5#(x2, y2) = #eval(input("Enter coords for side2:"))
c = 9.5, -3.4#(x3, y3) = #eval(input("Enter coords for side3:"))
# Calculate the length of the sides from the 3 triangle points
sideOne = math.sqrt( (b[0]-a[0])**2 + (b[1]-a[1])**2 )
sideTwo = math.sqrt( (c[0]-b[0])**2 + (c[1]-b[1])**2 )
sideThree = math.sqrt( (a[0]-c[0])**2 + (a[1]-c[1])**2 )
# Calculate s value
sideAll = (sideOne + sideTwo + sideThree) / 2 # Compute Area
area = math.sqrt(sideAll * (sideAll - sideOne) * (sideAll - sideTwo) * (sideAll - sideThree)) # Display Area
print("The Area of entered Triangle:", area)
참고 나는 math.sqrt
정수가 아닌 힘보다 함수 를 사용하는 것을 선호 하지만 이것은 단지 맛의 문제입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다