设为首页 加入收藏

TOP

C语言中的复数-C基础
2015-01-22 21:34:11 来源: 作者: 【 】 浏览:87
Tags:言中 复数 基础
复数:
?
?  复数比较详细的内容请参考:复数代数
?
  C支持复数的数学计算,复数Z可以在笛卡尔坐标表示为:Z=x+y*I;其中x和y是实数,I是虚数单位。数x被称为实部,数y为虚部。在 c语言中,一个复数是有浮点类型表示的实部和虚部。两部分都具有相同的类型,无论是float,double或者long double。
?
float _complex:实虚都为float
double _complex:实虚都为double
long double _complex:实虚都为long double
如果在c 源文件中包含了头文件 complex.h ,complex.h定义了complex 和 I宏。宏定义complex和一个关键字_complex 同义。我们可以用complex代替_complex.
?
下面是个简单的例子,运行在debian 7 (32bit)
?
?
?
?
详细代码:
?
?
复制代码
? 1 /*
? 2 ?* Title : Complex Numbers
? 3 ?* Description: Work with complex numbers in c
? 4 ?* Author:Eric.Lee
? 5 ?*
? 6 ?*/
? 7 #include
? 8 #include
? 9?
?10 #define Get_Array_Length(tempArray)(sizeof(tempArray)/sizeof(tempArray[0]))
?11?
?12 void GetResult(char operate,double complex x,double complex y)
?13 {
?14 ? ? double complex result = 0+0*I;
?15 ? ? switch(operate)
?16 ? ? {
?17 ? ? ? ? case '+':
?18 ? ? ? ? ? ? result = x+y;
?19 ? ? ? ? ? ? break;
?20 ? ? ? ? case '-':
?21 ? ? ? ? ? ? result = x-y;
?22 ? ? ? ? ? ? break;
?23 ? ? ? ? case '*':
?24 ? ? ? ? ? ? result = x*y;
?25 ? ? ? ? ? ? break;
?26 ? ? ? ? case '/':
?27 ? ? ? ? ? ? result =x/y;
?28 ? ? ? ? ? ? break;
?29 ? ? ? ? default:
?30 ? ? ? ? ? ? break;
?31 ? ? }
?32 ? ? printf("double complex x %c double complex y=%.2f+%.2fi\n",operate,creal(result),cimag(result));
?33?
?34 }
?35?
?36 int main()
?37 {
?38 ? ? double complex ?x = 10.0+15.0*I;
?39 ? ? double complex y = 20.0-5.0*I;
?40?
?41 ? ? printf("working with complex number:\n");
?42 ? ? printf("Starting values:x=%.2f+%.2fi\ty=%.2f +%.2fi\n",creal(x),cimag(x),creal(y),cimag(y));
?43 ? ? char operates[] = {'+','-','*','/'};
?44 ? ? char * op = operates;
?45 ? ? int i = 0;
?46 ? ? int operateLength = Get_Array_Length(operates);
?47 ? ? for(i=0;i<=operateLength-1;i++)
?48 ? ? {
?49 ? ? ? ? GetResult(*(op++),x,y);
?50 ? ? }
?51?
?52 ? ? return 0;
?53 } ? ?
复制代码
creal(x):得到复数的实部(对于 double),如果对于float,使用crealf(x),如果对于long double ,请使用 creall(x)
?
cimag(x):得到复数的虚部(对于double),如果对于float,使用crealf(x),如果对于long double ,请使用 creall(x)
?
此外还有一点值得注意的是:
?
              cos(), exp() 和 sqrt()同样也会有对应得复数方法,例如:ccos(),cexp(),csqrt()
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C语言快速排序算法代码分析 下一篇C语言优化实例:消除多级指针的间..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: