复数的加减乘除C语言实现

思路:
1复数的表示:用结构体实现
2复数的加减法:实部虚部分别相加减
复数的乘法:(a+bi)(c+di)=ac-bd+(ad+cb)i
复数的除法:(a+bi)(c+di)=(ac+bd)(c
c+dd)+(bc-ad)(cc+d*d)
考虑分母为0的情况
3用switch语句由用户自己选择要进行的操作
4用do…while循环实现多次运算

代码实现

#include<stdio.h>
#include<math.h>
//用结构体表示复数
typedef struct
{
    double realPart;
    double imagPart;
    /* data */
}complex;

//定义一个复数
complex assign(double a, double b);

//复数的加法
complex add(complex c1, complex c2);

//复数的减法
complex sub(complex c1, complex c2);

//复数的乘法
complex mul(complex c1, complex c2);

//复数的除法
complex div(complex c1, complex c2);

void display(complex c);

int main()
{
    double realPart, imagPart;
    complex c1, c2;
    int adjust=0;

    do
    {
        printf("--------------------------------\n");
        printf("欢迎您使用负数计算器\n");

        printf("请您输入复数的实部和虚部\n");
        scanf("%lf%lf", &realPart, &imagPart);
        c1 = assign(realPart, imagPart);
        display(c1);

        printf("请您输入第二个复数的实部和虚部\n");
        scanf("%lf%lf", &realPart, &imagPart);
        c2 = assign(realPart, imagPart);
        display(c2);

        
        printf("请您选择需要进行的操作\n");
        printf("1加法\n2减法\n3乘法\n4除法\n0退出复数计算器\n");
        scanf("%d", &adjust);

        if (adjust != 0)
        {
            printf("您的计算结果是:");
        }

        switch (adjust)
        {
        case 1:
            display(add(c1, c2));
            break;
        case 2:
            display(sub(c1, c2));
            break;
        case 3:
            display(mul(c1, c2));
            break;
        case 4:
            display(div(c1, c2));
            break;
        default:
            if (adjust == 0)
            {
                printf("谢谢使用");
            }
            else
            {
                printf("输入的操作有误,请您重新输入");
            }
        }
    } while (adjust != 0);

    printf("感谢您的使用,祝您生活愉快");
    return 0;
}

//定义一个复数
complex assign(double a, double b)
{
    complex c;
    c.realPart = a;
    c.imagPart = b;
    return c;
}

//复数的加法
complex add(complex c1, complex c2)
{
    assign((c1.realPart + c2.realPart), (c1.imagPart + c2.imagPart));
}

//复数的减法
complex sub(complex c1, complex c2)
{
   assign((c1.realPart - c2.realPart), (c1.imagPart - c2.imagPart));
}

//复数的乘法
complex mul(complex c1, complex c2)
{
    assign((c1.realPart * c2.realPart - c1.imagPart * c2.imagPart), (c1.imagPart * c2.realPart + c1.realPart * c2.imagPart));
}

//复数的除法
complex div(complex c1, complex c2)
{
    double temp = (pow(c1.imagPart, 2) + pow(c2.imagPart, 2));
    if (c2.imagPart!=0&&c2.realPart!=0)
    {
        assign((c1.realPart * c2.realPart + c1.imagPart * c2.imagPart) / temp, (c1.imagPart * c2.realPart - c1.realPart * c2.imagPart) / temp);
    }
    else
    {
        printf("除数为0,请重新输入");
    }
}

//输出复数
void display(complex c)
{
    printf("%lf+%lfi\n",c.realPart,c.imagPart);
}

运行结果显示:
复数的加减乘除C语言实现

上一篇:Kafka分区分配策略-RangeAssignor、RoundRobinAssignor、StickyAssignor


下一篇:软考2019下半年下午第三题