本题要求编写程序,计算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。
复杂重复的事情请交给函数!
#include<stdio.h>
#include<math.h>
#include<string.h>
void printFront(double a1, double b1, double a2, double b2, char c);
void printResult(double a, double b);
int main(void)
{
double a1, b1, a2, b2;
scanf_s("%lf %lf %lf %lf", &a1, &b1, &a2, &b2);
printFront(a1, b1, a2, b2, '+');
printResult(a1 + a2, b1 + b2);
printFront(a1, b1, a2, b2, '-');
printResult(a1 - a2, b1 - b2);
printFront(a1, b1, a2, b2, '*');
printResult(a1 * a2 - b1 * b2, b1 * a2 + a1 * b2);
printFront(a1, b1, a2, b2, '/');
printResult((a1 * a2 + b1 * b2) / (a2 * a2 + b2 * b2), (b1 * a2 - a1 * b2) / (a2 * a2 + b2 * b2));
return 0;
}
void printFront(double a1, double b1, double a2, double b2, char c)
{
if (b1 < 0 && b2 < 0) printf("(%.1f%.1fi) %c (%.1f%.1fi) = ", a1, b1, c, a2, b2);
else if (b1 < 0) printf("(%.1f%.1fi) %c (%.1f+%.1fi) = ", a1, b1, c, a2, b2);
else if (b2 < 0) printf("(%.1f+%.1fi) %c (%.1f%.1fi) = ", a1, b1, c, a2, b2);
else printf("(%.1f+%.1fi) %c (%.1f+%.1fi) = ", a1, b1, c, a2, b2);
}
void printResult(double a, double b)
{
if ((a <= 0.05 && a >= -0.05) && (b <= 0.05 && b >= -0.05)) printf("0.0\n"); //浮点数有偏差,保留一位则只要小于0.05的绝对值即可
else if ((a <= 0.05 && a >= -0.05)) printf("%.1fi\n", b);
else if ((b <= 0.05 && b >= -0.05)) printf("%.1f\n", a);
else if (b <= 0.05) printf("%.1f%.1fi\n", a, b);
else printf("%.1f+%.1fi\n", a, b);
}