定義一個struct作為複數,然後分別定義加減剩除運算。可以增加一個函式printcomplex來在主函式中以數學的形式輸出複數。
typedef struct complex
{
double real; //實部
double image; //虛部
} COMPLEX;
COMPLEX add(COMPLEX a,COMPLEX b) //加法
COMPLEX sum;
sum.real = a.real+b.real;
sum.image = a.image+b.image;
return sum;
}
COMPLEX sub(COMPLEX a,COMPLEX b) //減法
COMPLEX diff;
diff.real = a.real-b.real;
diff.image = a.image-b.image;
return diff;
COMPLEX mul(COMPLEX a,COMPLEX b) //乘法
COMPLEX acc;
acc.real = a.real*b.real-a.image*b.image;
acc.image = a.real*b.image+a.image*b.real;
return acc;
COMPLEX divi(COMPLEX a,COMPLEX b) //除法
//除法去分母可以轉換為乘法
COMPLEX quo;
double den = b.real*b.real+b.image*b.image; //分母
/* 先判斷除數是否為0,因為均為double型,所以不能 直接與0作比較,而要用絕對值是否小於某個極小值e(讀伊夫西龍???)來判斷是否為0,這裡取e=10e-10 */
if ((abs(b.real)<10e-10) && (abs(b.image)<10e-10))
printf("Divivd by Zero");
exit(0); //強制退出程式
quo.real = a.real*b.real+a.image*b.image;
quo.real /= den;
quo.image = a.image*b.real+a.real*b.image;
quo.image /= den;
return quo;
void printcom(COMPLEX a) //輸出複數a
printf("%lf+%lfi",a.real,a.image);
定義一個struct作為複數,然後分別定義加減剩除運算。可以增加一個函式printcomplex來在主函式中以數學的形式輸出複數。
typedef struct complex
{
double real; //實部
double image; //虛部
} COMPLEX;
COMPLEX add(COMPLEX a,COMPLEX b) //加法
{
COMPLEX sum;
sum.real = a.real+b.real;
sum.image = a.image+b.image;
return sum;
}
COMPLEX sub(COMPLEX a,COMPLEX b) //減法
{
COMPLEX diff;
diff.real = a.real-b.real;
diff.image = a.image-b.image;
return diff;
}
COMPLEX mul(COMPLEX a,COMPLEX b) //乘法
{
COMPLEX acc;
acc.real = a.real*b.real-a.image*b.image;
acc.image = a.real*b.image+a.image*b.real;
return acc;
}
COMPLEX divi(COMPLEX a,COMPLEX b) //除法
//除法去分母可以轉換為乘法
{
COMPLEX quo;
double den = b.real*b.real+b.image*b.image; //分母
/* 先判斷除數是否為0,因為均為double型,所以不能 直接與0作比較,而要用絕對值是否小於某個極小值e(讀伊夫西龍???)來判斷是否為0,這裡取e=10e-10 */
if ((abs(b.real)<10e-10) && (abs(b.image)<10e-10))
{
printf("Divivd by Zero");
exit(0); //強制退出程式
}
quo.real = a.real*b.real+a.image*b.image;
quo.real /= den;
quo.image = a.image*b.real+a.real*b.image;
quo.image /= den;
return quo;
}
void printcom(COMPLEX a) //輸出複數a
{
printf("%lf+%lfi",a.real,a.image);
}