9-2 計算兩個複數之積
阿新 • • 發佈:2018-12-01
// 計算兩個複數之積 #include <stdio.h> #include <math.h> struct Complex { double real; double imag; }; void Multiply(struct Complex *p, struct Complex c1, struct Complex c2); void Show(struct Complex c); int main(void) { struct Complex c1,c2,c3; printf("請輸入第一個複數的實部和虛部: "); scanf("%lf%lf",&c1.real,&c1.imag); printf("請輸入第二個複數的實部和虛部: "); scanf("%lf%lf",&c2.real,&c2.imag); Multiply(&c3,c1,c2); //複數相乘 Show(c3); //顯示結果 return 0; } void Multiply(struct Complex *p, struct Complex c1, struct Complex c2) { p->real = c1.real*c2.real-c1.imag*c2.imag; p->imag = c1.real*c2.imag+c1.imag*c2.real; } void Show(struct Complex c) { // 實部和虛部均為0 if (fabs(c.real)<1e-4&&fabs(c.imag)<1e-4) { printf("兩數相乘結果為: 0\n"); } // 實部為0,虛部不為0 else if (fabs(c.real)<1e-4) { printf("兩數相乘結果為: %fi\n",c.imag); } // 實部不為0,虛部為0 else if (fabs(c.imag)<1e-4) { printf("兩數相乘結果為: %f\n",c.real); } // 實部不為0,虛部大於0 else if (c.imag>0) { printf("兩數相乘結果為: %f+%fi\n",c.real,c.imag); } // 實部不為0,虛部小於0 else { printf("兩數相乘結果為: %f%fi\n",c.real,c.imag); } }