今天我在C中乱搞复杂的数字,所以(很自然地)我尝试用Euler的身份编程.我们都知道eiπ = -1但是由于某种原因C想要返回(正)1 - 为什么呢?谢谢!
#include <stdio.h>
#include <math.h>
#include <complex.h>
double main(void){
double complex exponent = M_PI*I;
double complex power = exp(exponent);
printf("%.f\n",power);
return power;
}
Run Code Online (Sandbox Code Playgroud)
复杂的数字被强制转化为真实因为exp期待一个double论点.coersion丢弃虚部,只传递真实部分0.因此,exp(0) = 1.
你应该使用cexp而不是exp. cexp期待一个double complex.
您也不应该complex直接传递printf,但应明确打印实部和虚部,如下所示:
#include <stdio.h>
#include <math.h>
#include <complex.h>
double main(void){
double complex exponent = M_PI*I;
double complex power = cexp(exponent);
printf("%.f + %.fi\n", creal(power), cimag(power));
return power;
}
Run Code Online (Sandbox Code Playgroud)
此外,返回double从main只是普通的怪异...