計算三角形面積周長

一.代碼
import math
a=float(input("請輸入三角形的邊:"))
b=float(input("請輸入三角形的邊:"))
c=float(input("請輸入三角形的邊:"))
print("三角形的三邊:",a,b,c)
if(a>0 and b>0 and c>0 and a+b>c and a+c>b and b+c>a):
    l=a+b+c
    h=l/2
    s=math.sqrt(h*(h-a)*(h-b)*(h-c))
    print("三角形的周長=%.2f,面積=%.2f"%(l,s))
else:
    print("無法構成三角形")


二.運行結果

請輸入三角形的邊:3
請輸入三角形的邊:4
請輸入三角形的邊:5
三角形的三邊: 3.0 4.0 5.0
三角形的周長=12.00,面積=6.00

三.問題
  (1) print格式控制輸出

  (2) 重複執行程序

四.解決

 1. 打印字符串
print ("His name is %s"%("Aviad"))

效果:

2.打印整數

print ("He is %d years old"%(25))

效果:

3.打印浮點數

print ("His height is %f m"%(1.83))

效果:

4.打印浮點數(指定保留小數點位數)

print ("His height is %.2f m"%(1.83))

效果:

5.指定佔位符寬度

print ("Name:%10s Age:%8d Height:%8.2f"%("Aviad",25,1.83))

效果:

6.指定佔位符寬度(左對齊)

print ("Name:%-10s Age:%-8d Height:%-8.2f"%("Aviad",25,1.83))

效果:

7.指定佔位符(只能用0當佔位符?)

print ("Name:%-10s Age:%08d Height:%08.2f"%("Aviad",25,1.83))

效果:

8.科學計數法

format(0.0015,'.2e')

效果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章