Python 計算三角形的面積

Document 對象參考手冊 Python3 實例

以下實例為通過用戶輸入三角形三邊長度,並計算三角形的面積:

實例(Python 3.0+)

# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.xuhuhu.com a = float(input('輸入三角形第一邊長: ')) b = float(input('輸入三角形第二邊長: ')) c = float(input('輸入三角形第三邊長: ')) # 計算半周長 s = (a + b + c) / 2 # 計算面積 area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('三角形面積為 %0.2f' %area)

執行以上代碼輸出結果為:

$ python test.py
輸入三角形第一邊長: 5
輸入三角形第二邊長: 6
輸入三角形第三邊長: 7
三角形面積為 14.70

Document 對象參考手冊 Python3 實例