算法提高 6-17复数四则运算
时间限制:1.0s 内存限制:512.0MB
设计复数库,实现基本的复数加减乘除运算。
输入时只需分别键入实部和虚部,以空格分割,两个复数之间用运算符分隔;输出时按a+bi的格式在屏幕上打印结果。参加样例输入和样例输出。
注意考虑特殊情况,无法计算时输出字符串"error"。
样例输入
2 4 * -3 2
样例输出
-14-8i
样例输入
3 -2 + -1 3
样例输出
2+1i
分析:复数的四则运算公式见注释,代码如下:
PS:刚开始在输出error的位置我return了-1,代表是错误,结果提交上去老是运行错误。后来猜测是蓝桥判断了main的返回值,必须为0才不会运行错误,改为return 0之后果然正确了。(~ ̄▽ ̄)~
特此提醒一下那些和我一样习惯出错就return -1的小伙伴,注意一下哈~
#include <iostream>
using namespace std;
//复数类
struct fushu
{ //a+bi;
double a;
double b;
};
//复数的加法运算:(a+bi)+(c+di) = (a+c)+(b+d)i
fushu *add(fushu *y1, fushu *y2)
{
fushu *temp = new fushu;
temp->a = y1->a + y2->a;
temp->b = y1->b + y2->b;
return temp;
}
//复数的减法运算:(a+bi)-(c+di) = (a-c)+(b-d)i
fushu *jian(fushu *y1, fushu *y2)
{
fushu *temp = new fushu;
temp->a = y1->a - y2->a;
temp->b = y1->b - y2->b;
return temp;
}
//复数的乘法运算:(a+bi)*(c+di) = (ac-bd) + (ad-bc)i
fushu *cheng(fushu *y1, fushu *y2)
{
fushu *temp = new fushu;
temp->a = y1->a * y2->a - y1->b * y2->b;
temp->b = y1->a * y2->b + y1->b * y2->a;
return temp;
}
//复数的除法运算:(a+bi)/(c+di) = (ac+bd)/(c*c+d*d)+(bc-ad)/(c*c+d*d)i
fushu *chu(fushu *y1, fushu *y2)
{
fushu *temp = new fushu;
//注意分母不能为0
if(y2->a == 0 && y2->b == 0)
{
return NULL;
}
temp->a = (y1->a * y2->a + y1->b * y2->b)/(y2->a * y2->a + y2->b * y2->b);
temp->b = (y1->b * y2->a - y1->a * y2->b)/(y2->a * y2->a + y2->b * y2->b);
return temp;
}
int main()
{
fushu *y1 = new fushu;
fushu *y2 = new fushu;
fushu *result;
char ch;
cin >> y1->a >> y1->b >> ch >> y2->a >> y2->b;
switch(ch)
{
case '+': result = add(y1, y2); break;
case '-': result = jian(y1, y2); break;
case '*': result = cheng(y1, y2); break;
case '/': result = chu(y1, y2); break;
default: result = NULL;
}
if(!result) //如果result == NULL,则报错
{
cout << "error";
return 0;
}
cout << result->a;
if(result->b > 0) cout << "+"; //如果是正数,则前面补‘+’号,负数自带‘-’号
cout << result->b << "i";
return 0;
}