《python語言程序設計》_第二章編程題


2.1

程序:

Celsius=eval(input("Enter a degree in Celsius:"))
#輸入攝氏度的值Celsius
fahrenheit =(9/5)*Celsius + 32
#定義華氏溫度fahrenheit
print(Celsius,"Celsius is",fahrenheit,"Fahrenheit")

結果:

Enter a degree in Celsius:43
43 Celsius is 109.4 Fahrenheit

2.2 讀取半徑和高來計算圓柱體底面面積和體積

設計:

area = radius * radius *∏ 

volume =area * length 

程序:

radius,length = eval (input("Enter the radius and length of cylinder:" ))
#輸入半徑radius和高length
area = radius*radius*3.14
#定義面積公式
volume = area * length
#定義圓柱體的體積
print("The area is",area)
print("The volume is",volume)

結果:

Enter the radius and length of cylinder:5.5,12
The area is 94.985
The volume is 1139.82

2.3 英尺轉米尺,一英尺等於0.305米

程序:

feet = eval(input("Enter a value for feet:"))
meters=feet*0.305
print(feet,"feet is",meters,"meters")

結果:

Enter a value for feet:16.5
16.5 feet is 5.0325 meters

2.4

磅數 轉換成千克數,一磅等於0.454千克

 程序:

feet = eval(input("Enter a value for feet:"))
meters=feet*0.305
print(feet,"feet is",meters,"meters")

結果:

Enter a value for feet:16.5
16.5 feet is 5.0325 meters

2.5

編寫一個讀取小計和酬金然后計算小費以及合計金額的程序,如果用戶鍵入的小計是10,酬金率是15%,程序就會顯示是1.5,合計金額是11.5

 

程序:

 

subtotal,gratuityRate=eval(input("Enter the subtotal and a gratuity rate:"))
gratuity= subtotal*gratuityRate/100
total=gratuity+subtotal
print("The gratuity is",gratuity,"and the total is",total)

結果:

Enter the subtotal and a gratuity rate:15.69,15
The gratuity is 2.3535 and the total is 18.043499999999998

2.6  讀取一個0到1000之間的整數並計算它各位數字之和,例如:如果一個整數是932,那么它各位數字之和就是14。(提示:使用%來提取數字,使用//運算符來去除被提取的數字。例如:932%10=2而932//10=93)

程序:

A=eval(input("Enter a numer between 0 and 1000:"))
b=A%10 #運算符%求余符號,A%100得到的余數是A的個位數,int()函數表示去掉了浮點數,取整
c=A//100 #運算符//是表示整除,得到的相當於A的百位數
d=(A-100*b-c)/10    #或者,(((A-b)/10)%10)  
print("The sum of the digits is",int(b+c+d))

 結果:

 

Enter a numer between 0 and 1000:999
The sum of the digits is 27

2.7 輸入分鍾數,計算年數和天數

答案略

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM