7-36 复数四则运算 (15 分)(python编写)
生活随笔
收集整理的這篇文章主要介紹了
7-36 复数四则运算 (15 分)(python编写)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本題要求編寫程序,計算2個復數的和、差、積、商。
輸入格式:
輸入在一行中按照a1 b1 a2 b2的格式給出2個復數C1=a1+b1i和C2=a2+b2i的實部和虛部。題目保證C2不為0。
輸出格式:
分別在4行中按照(a1+b1i) 運算符 (a2+b2i) = 結果的格式順序輸出2個復數的和、差、積、商,數字精確到小數點后1位。如果結果的實部或者虛部為0,則不輸出。如果結果為0,則輸出0.0。
題目分析:
python 可以直接用復數做四則運算,撿了個大便宜,但比較坑的是 python 用 j 表示虛數單位,和用 i 表示虛數單位的數學習慣不一樣,需要轉換一下。
#test7-36.py# in this function the parameter type is str def userComplex(real, imag):if eval(imag)<0:z = real + imag + "j"else:z = real + "+" + imag + "j"return eval(z)# in this function the parameter type is complex def resultFormat(z):if z.real == 0 and z.imag == 0:print("0.0")elif z.real == 0 and z.imag != 0:print("{:.1f}i".format(z.imag))elif z.real != 0 and z.imag == 0:print("{:.1f}".format(z.real))else:if z.imag < 0:print("{:.1f}".format(z.real) + "{:.1f}i".format(z.imag))else:print("{:.1f}".format(z.real) + "+" + "{:.1f}i".format(z.imag))# in this function the parameter type is complex def userFormat(z):a = "{:.1f}".format(z)a = a[0:-1] + "i"a = "("+a+")"return auserInput = input().split() z1 = userComplex(userInput[0], userInput[1]) z2 = userComplex(userInput[2], userInput[3]) a1 = userFormat(z1) a2 = userFormat(z2) sum = eval("{:.1f}".format(z1 + z2)) diff = eval("{:.1f}".format(z1 - z2)) product = eval("{:.1f}".format(z1 * z2)) quotient = eval("{:.1f}".format(z1 / z2)) result = [sum, diff, product, quotient] oper = [" + "," - "," * "," / "]for i in range(4):print(a1+oper[i]+a2+" = ", end="")resultFormat(result[i])總結
以上是生活随笔為你收集整理的7-36 复数四则运算 (15 分)(python编写)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 敏捷开发系列之旅 第三站(认识FDD特征
- 下一篇: 动态网页制作怎么这么难