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 a

userInput = 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])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值