题目:
计算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
思路:
首先输入四个数字,然后先输出对应的四个运算式子,最后对应的函数分别进行运算,讲运算出来的虚部和实部传入一个函数,根据题目要求,将运算后的四个答案分别输出即可。
AC代码:
#include<string>
#include<iostream>
using namespace std;
string op1, op2; //控制打印时的加减符号输出
double a1, b1, a2, b2; //两个复数的四个数
void symbol() //控制打印时的加减符号输出
{
if (b1 >= 0)
op1 = "+";
else
op1 = "";
if (b2 >= 0)
op2 = "+";
else
op2 = "";
}
void Output(double real, double imag) //控制结果输出函数
{
cout.precision(1); //控制输出浮点数的精确度
if ((int)(real * 10) == 0) //实部为0
{
if ((int)(imag * 10) == 0) //实部和虚部都是0
cout << 0.0;
else
cout << fixed << imag << 'i';
}
else if ((int)(imag * 10) == 0) //虚部为0
cout << fixed << real;
else
{
cout << fixed << real;
if (imag >= 0)
cout << '+';
cout << fixed << imag << 'i';
}
}
void Add() //加法计算:(a+bi)+(c+di)=(a+c)+(b+d)i
{
double real = a1 + a2;
double imag = b1 + b2;
Output(real, imag);
}
void Subtraction() //减法计算: (a+bi)-(c+di)=(a-c)+(b-d)i
{
double real = a1 - a2;
double imag = b1 - b2;
Output(real, imag);
}
void Multiply() //乘法计算:(a+bi)(c+di)=(ac-bd)+(bc+ad)i
{
double real = a1 * a2 - b1 * b2;
double imag = a1 * b2 + a2 * b1;
Output(real, imag);
}
void Divide() //除法计算:(a+bi)/(c+di)=(ac+bd)/(c^2+d^2) +((bc-ad)/(c2+d2))i
{
double deno = a2 * a2 + b2 * b2;
double real = (a1*a2 + b1 * b2) / deno;
double imag = (a2*b1 - a1 * b2) / deno;
Output(real, imag);
}
int main(void)
{
cout << "请输入四个数字:";
cin >> a1 >> b1 >> a2 >> b2;
symbol();
cout.precision(1); //控制输出浮点数的精确度
cout << fixed << '(' << a1 << op1 << b1 << "i) " << "+ (" << a2 << op2 << b2 << "i) = ";
Add(); cout << endl;
cout << fixed << '(' << a1 << op1 << b1 << "i) " << "- (" << a2 << op2 << b2 << "i) = ";
Subtraction(); cout << endl;
cout << fixed << '(' << a1 << op1 << b1 << "i) " << "* (" << a2 << op2 << b2 << "i) = ";
Multiply(); cout << endl;
cout << fixed << '(' << a1 << op1 << b1 << "i) " << "/ (" << a2 << op2 << b2 << "i) = ";
Divide(); cout << endl;
return 0;
}
来源:CSDN
作者:绯樱殇雪
链接:https://blog.csdn.net/qq_41918107/article/details/103949546