今天我在用 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;
}
最佳答案
复数被强制转换为实数,因为 exp
需要一个 double
参数。强制转换丢弃虚部,仅传递实部,即 0
。因此,exp(0) = 1
。
您应该使用 cexp
而不是 exp
。 cexp
需要一个 double 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;
}
此外,从 main
返回一个 double
很奇怪......
关于c - C语言中的欧拉恒等式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43828662/