撰寫一個檔案名為except-multiple.py的程式,以完成如下三個運算式的計算:
a/(a-b-1)
math.sqrt(a**2-b**2)
a**b
要求:a、b兩變數中的數,由用戶輸入:
它們可以是浮點數;
a和b都必須大于20;
捕捉Ctrl+Z鍵;
如果有錯,讓用戶繼續重新輸入;
允許用戶按Ctrl+C鍵中斷程式,但必須輸出提示;
每次犯錯都輸出累積的犯錯次數,最后成功完成任務時,要是曾經犯過錯,還要輸出一次犯錯次數。
可能的運行結果如下:
第一個數:18
第二個數:19
第一個數必須大于第二個數!
你犯了1次錯誤!
第一個數:19
第二個數:18
每個數都必須大于20!
你犯了2次錯誤!
第一個數:28
第二個數:27
除數不能為0!
你犯了3次錯誤!
第一個數:me
第二個數:19
請使用半角的阿拉伯數字!
你犯了4次錯誤!
第一個數:^Z
不要沒事按Ctrl+Z!
你犯了5次錯誤!
第一個數:20000
第二個數:200
20000.000000÷(20000.000000-200.000000-1)=1.010152
math.sqrt(20000.000000**2-200.000000**2)=19998.999975
你所輸入的數字太大了!
你犯了6次錯誤!
第一個數:28
第二個數:22
28.000000÷(28.000000-22.000000-1)=5.600000
math.sqrt(28.000000**2-22.000000**2)=17.320508
28.000000**22.000000=68782299287045578092179575799808.000000
你犯了6次錯誤!
任務完成!
(快來救救孩子)
uj5u.com熱心網友回復:
#coding:utf-8import math
err=0
def error(code):
global err
if code==1:
print("第一個數必須大于第二個數!")
elif code==2:
print("每個數都必須大于20!")
elif code==3:
print("除數不能為0!")
elif code==4:
print("請使用半角的阿拉伯數字!")
elif code==5:
print("不要沒事按Ctrl+Z!")
elif code==6:
print("你所輸入的數字太大了!")
err+=1
print("你犯了"+str(err)+"次錯誤!")
def read():
try:
a=input()
except EOFError:
error(5)
return -1
try:
b=input()
except EOFError:
error(5)
return -1
try:
a=float(a)
b=float(b)
except ValueError:
error(4)
return -1
if a<b:
error(1)
return -1
if a<20 or b<20:
error(2)
return -1
try:
i=a/(a-b-1)
except ZeroDivisionError:
error(3)
return -1
y=math.sqrt(a**2-b**2)
print("{:6f}÷({:6f}-{:6f}-1)={:6f}".format(a,a,b,i))
print("math.sqrt({:6f}**2-{:6f}**2)={:6f}".format(a,b,y))
if y>10000:
error(6)
return -1
x=a**b
print("{:6f}**{:6f}={:6f}".format(a,b,x))
return 0
def main():
try:
while True:
if read()==0:
break
print("你犯了"+str(err)+"次錯誤!")
print("任務完成!")
return 0
except KeyboardInterrupt:
print("你按下了CTRL+C!")
return -1
except:
print("未知錯誤")
return -2
if __name__=="__main__":
import sys
sys.exit(main())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/43384.html
