算法训练 P1103
时间限制:1.0s 内存限制:256.0MB
提交此题
编程实现两个复数的运算。设有两个复数 和 ,则他们的运算公式为:
要求:(1)定义一个结构体类型来描述复数。
(2)复数之间的加法、减法、乘法和除法分别用不用的函数来实现。
(3)必须使用结构体指针的方法把函数的计算结果返回。
说明:用户输入:运算符号(+,-,*,/) a b c d.
输出:a+bi,输出时不管a,b是小于0或等于0都按该格式输出,输出时a,b都保留两位。
输入:
- 2.5 3.6 1.5 4.9
输出:
1.00±1.30i
分析:按照要求做就好了,唯一的知识点可能就是复数的运算了吧。公式在注释里,代码如下:
#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;
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 >> ch >> y1->a >> y1->b >> 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: break;
}
printf("%0.2lf+%0.2lfi", result->a, result->b);
return 0;
}