用C來寫複數

GNU C99以前通常是用結構(struct)來表示,簡單的例子如下
------------------------------------------------------ 
#include < stdio.h >

struct my_complex {
double real;
double imag;
};
int main(void){
struct my_complex z = {42.0, 42.0};

printf("z = %f + %fI\n",x.real, x.imag);

return 0;
}
-----------------------------------------------------
C99提供了一個方便的表示方法,在complex.h裡面
#include < stdio.h >
#include < complex.h >
int main (void){
complex double z = 42.0 + 42.0*I;

printf("z = %f + %fI\n", creal(z), cimag(z));

return 0;
}
----------------------------------------------------- 
— Function: double creal (complex double z) 
— Function: float crealf (complex float z) 
— Function: long double creall (complex long double z)These functions return the real part of the complex number z.
— Function: double cimag (complex double z) 
— Function: float cimagf (complex float z) 
— Function: long double cimagl (complex long double z)These functions return the imaginary part of the complex number z.
 
詳細的內容可以參考:
http://www.gnu.org/s/libc/manual/html_node/Complex-Numbers.html#Complex-Numbers 

沒有留言:

張貼留言