算法提高 6-17复数四则运算

时间限制:1.0s   内存限制:512.0MB

 

  设计复数库,实现基本的复数加减乘除运算。
  输入时只需分别键入实部和虚部,以空格分割,两个复数之间用运算符分隔;输出时按a+bi的格式在屏幕上打印结果。参加样例输入和样例输出。
  注意考虑特殊情况,无法计算时输出字符串"error"。

 

样例输入

2 4 * -3 2

样例输出

-14-8i

样例输入

3 -2 + -1 3

样例输出

2+1i

 

注意:题目中并没有提及输出结果的输出精度,故这里对于C语言实现,printf函数里的format串应为"%g",即自动选择合适的有效数字。

 

#include <stdio.h>

struct Complex
{
    double real;
    double img;
};

void add(struct Complex a, struct Complex b)
{
    struct Complex ans;
    ans.real = a.real + b.real;
    ans.img = a.img + b.img;
    printf("%g%+gi", ans.real, ans.img);
}

void sub(struct Complex a, struct Complex b)
{
    struct Complex ans;
    ans.real = a.real - b.real;
    ans.img = a.img - b.img;
    printf("%g%+gi", ans.real, ans.img);
}

void mul(struct Complex a, struct Complex b)
{
    struct Complex ans;
    ans.real = a.real * b.real - a.img * b.img;
    ans.img = a.real * b.img + a.img * b.real;
    printf("%g%+gi", ans.real, ans.img);
}

void div(struct Complex a, struct Complex b)
{
    struct Complex ans;
    if (b.real == 0 && b.img == 0)
        printf("error");
    else
    {
        ans.real = (a.real * b.real + a.img * b.img) / (b.real * b.real + b.img * b.img);
        ans.img = (a.img * b.real - a.real * b.img) / (b.real * b.real + b.img * b.img);
        printf("%g%+gi", ans.real, ans.img);
    }
}

int main()
{
    struct Complex a, b;
    char op;

    scanf("%lf %lf %c %lf %lf", &a.real, &a.img, &op, &b.real, &b.img);
    if (op == '+')
        add(a, b);
    else if (op == '-')
        sub(a, b);
    else if (op == '*')
        mul(a, b);
    else
        div(a, b);

    return 0;
}