PTA 基础编程题 7-36 复数四则运算 (15 point(s))

PTA 专栏收录该内容
189 篇文章 2 订阅

7-36 复数四则运算 (15 point(s))

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

思路:

不难,但是有点麻烦需要注意的是如果数值的绝对值小于0.1,即等于0,运算不难,主要在数值的输入,输出上面有点坑

#include <bits/stdc++.h>
using namespace std;
struct num{
	double real;
	double image;
};
num c1, c2;
void print(double a, double b, char c) {
	bool flag = false;
	if (c1.image >= 0 && c2.image >=0)              
        printf("(%.1lf+%.1lfi) %c (%.1lf+%.1lfi) = ", c1.real, c1.image, c, c2.real, c2.image);
    else if (c1.image >= 0 && c2.image < 0)
        printf("(%.1lf+%.1lfi) %c (%.1lf%.1lfi) = ", c1.real, c1.image, c, c2.real, c2.image);
    else if (c1.image < 0 && c2.image >= 0)
        printf("(%.1lf%.1lfi) %c (%.1lf+%.1lfi) = ", c1.real, c1.image, c, c2.real, c2.image);
    else 
        printf("(%.1lf%.1lfi) %c (%.1lf%.1lfi) = ", c1.real, c1.image, c, c2.real, c2.image);
	if (fabs(a) < 0.1 && fabs(b) < 0.1) {
		cout << "0.0\n";
		return ;
	}
	if (fabs(a) >= 0.1) {
		printf("%.1lf", a);
		flag = true;
	}
	if (fabs(b) >= 0.1) {
		if(flag && b > 0.0) printf("+%.1lfi", b);
		else printf("%.1lfi", b);
	}
	cout << endl;
}
void add(num a, num b) {
	double really = a.real + b.real;
	double imagen = a.image + b.image;
	print(really, imagen, '+'); 
}
void minu(num a, num b) {
	double really = a.real - b.real;
	double imagen = a.image - b.image;
	print(really, imagen, '-'); 
}
void multi(num a, num b) {
	double really = - a.image * b.image + a.real * b.real;
	double imagen = a.image * b.real + a.real * b.image;
	print(really, imagen, '*');
}
void divide(num a, num b) {
	double di = b.real * b.real + b.image * b.image;
	double really = (a.image * b.image + a.real * b.real) / di;
	double imagen = (a.image * b.real - a.real * b.image) / di;
	print(really, imagen, '/');
}
int main() {
	cin >> c1.real >> c1.image >> c2.real >> c2.image;
	add(c1, c2);
	minu(c1, c2);
	multi(c1, c2);
	divide(c1, c2);
	return 0;
}
  • 3
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值