设计一个复数类.从键盘输入2个复数,完成复数的加减运算,然后输出运算结果.

1个回答

  • #include

    struct complex

    {

    double real;

    double imaginary;

    };

    struct complex input(void)

    {

    struct complex num;

    printf("input complex number (eg.2.0+1.1i):");

    scanf("%lf+%lfi",&num.real,&num.imaginary);

    return num;

    }

    struct complex plus(struct complex a,struct complex b)

    {

    struct complex num;

    num.real = a.real + b.real;

    num.imaginary = a.imaginary + b.imaginary;

    return num;

    }

    struct complex minus(struct complex a,struct complex b)

    {

    struct complex num;

    num.real = a.real - b.real;

    num.imaginary = a.imaginary - b.imaginary;

    return num;

    }

    void output(struct complex a)

    {

    printf("%lf + %lfin",a.real,a.imaginary);

    }

    int main()

    {

    struct complex n1,n2,sum,dif;

    n1 = input();

    printf("you inputed ");

    output(n1);

    n2 = input();

    printf("you inputed ");

    output(n2);

    sum = plus(n1,n2);

    printf("sum is ");

    output(sum);

    dif = minus(n1,n2);

    printf("dif is ");

    output(dif);

    }

    /tmp/c2> xx19

    input complex number (eg.2.0+1.1i):2.0+1.1i

    you inputed 2.000000 + 1.100000i

    input complex number (eg.2.0+1.1i):42.0+3.2i

    you inputed 42.000000 + 3.200000i

    sum is 44.000000 + 4.300000i

    dif is -40.000000 + -2.100000i