7-1 复数四则运算

本题要求编写程序,计算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。

输入样例1:

2 3.08 -2.04 5.06

输出样例1:

(2.0+3.1i) + (-2.0+5.1i) = 8.1i
(2.0+3.1i) - (-2.0+5.1i) = 4.0-2.0i
(2.0+3.1i) * (-2.0+5.1i) = -19.7+3.8i
(2.0+3.1i) / (-2.0+5.1i) = 0.4-0.6i

输入样例2:

1 1 -1 -1.01

输出样例2:

(1.0+1.0i) + (-1.0-1.0i) = 0.0
(1.0+1.0i) - (-1.0-1.0i) = 2.0+2.0i
(1.0+1.0i) * (-1.0-1.0i) = -2.0i
(1.0+1.0i) / (-1.0-1.0i) = -1.0

关于本题,我认为有三点需要注意:

  1. 注意此程序接受多位小数输入,但输出保持一位小数;
  2. 此题是将计算结果四舍五入保留一位小数;
  3. 关于复数虚部符号问题我们使用格式化输出(见程序中代码)。

其次是输出问题:
要判断实部和虚部是否同时为零或者有一个为零的不同情况。

所以本题将要编写两个函数,一个是判断函数(判断实部和虚部),另一个是四舍五入函数。

代码如下:

#include <stdio.h>
#include <stdlib.h>
typedef struct complex            //定义复数结构体
{
	double s;
	double x;
}com;
int judge(double s, double x)        //判断输出状态函数
{
	if (s == 0 && x == 0)
		return 1;
	else if (s == 0 && x != 0)
		return 2;
	else if (s != 0 && x == 0)
		return 3;
	else if (s != 0 && x != 0)
		return 4;
}
double qu(double a)                    //四舍五入函数
{
    double b=(int)(a*10)/10;
    double s=a*100;
    int p=(int)s%10;
    if(abs(p)>=5)
        return a<0?(b-0.1):(b+0.1);
    else if(b==0)
        return 0;
    else if(abs(p)<5 && abs(p)>0)
        return b;
    else if(abs(p)==0)
        return a;
}
int main(void)
{
	com a1, a2;
	scanf("%lf %lf %lf %lf",&a1.s, &a1.x, &a2.s, &a2.x);
	//加法
	double sum_s = a1.s + a2.s;
	double sum_x = a1.x + a2.x;
	//减法
	double del_s = a1.s - a2.s;
	double del_x = a1.s - a2.x;
	//乘法
	double mul_s = a1.s*a2.s - a1.x*a2.x;
	double mul_x = a1.x*a2.s + a1.s*a2.x;
	//除法
	double div_s = (a1.s*a2.s+a1.x*a2.x) / (a2.s*a2.s+a2.x*a2.x);
	double div_x = (a1.x*a2.s-a1.s*a2.x) / (a2.s*a2.s+a2.x*a2.x);

	com f[4] = {{sum_s, sum_x},{del_s, del_x}, {mul_s, mul_x}, {div_s, div_x}};
	char ch[4] = {'+','-','*','/'};
	int i;
	for(int i=0; i<4; i++)                     //输出循环  
    {
        if(judge(qu(f[i].s), qu(f[i].x))==2)
            printf("(%.1lf%+.1lfi) %c (%.1lf%+.1lfi) = %.1lfi\n", a1.s, a1.x, ch[i], a2.s, a2.x, f[i].x);
        else if(judge(qu(f[i].s), qu(f[i].x))==3)
            printf("(%.1lf%+.1lfi) %c (%.1lf%+.1lfi) = %.1lf\n", a1.s, a1.x, ch[i], a2.s, a2.x, f[i].s);
        else if(judge(qu(f[i].s), qu(f[i].x))==1)
            printf("(%.1lf%+.1lfi) %c (%.1lf%+.1lfi) = 0.0\n", a1.s, a1.x, ch[i], a2.s, a2.x);
        else if(judge(qu(f[i].s), qu(f[i].x))==4)
            printf("(%.1lf%+.1lfi) %c (%.1lf%+.1lfi) = %.1lf%+.1lfi\n", a1.s, a1.x, ch[i], a2.s, a2.x, f[i].s, f[i].x);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值