2017-04-04 136 views
1

用户打算给出“x”和“n”的值以便使用taylors系列近似计算cos x(您可以在此处查看其公式:http://campusdematematicas.com/wp-content/uploads/2012/05/serie-taylor-funcion-coseno.gif )其中“k”值是下面代码中的“i”。尝试使用泰勒公式生成cos x的值

事情是,我不知道我做错了什么,因为它没有给我cos x的正确值。

我刚刚尝试的输入是x = 3.14,n = 6。 它应该给我的结果是cosx = -1.00 相反,它给了我:1.14

顺便说一句,它不会为0的工作,因为它应该让COS(X)= 1.00, 并且它给出0.000000而不是

#include <stdio.h> 

int main(){ 
double x, n, m; 
int i = 0, j, l, k = -1; 
double g = 0.0; 
unsigned long long p = 1; 
printf("Introduce the value of x (real): "); 
scanf("%lf%*c", &x); 
m = x; 
printf("\nIIntroduce the value of n (natural): "); 
scanf("%lf%*c", &n); 

while (i <=n){ 

    for (l=1; l < (i*2); l++){ 
    m *= x; 
    } 

    for (j=1; j <= (2*i); j++){ 
     p *=j; 

    } 
    if (i%2 == 0){ 
     k = 1; 
    } 

    g += (double) (m/p)*(k); 
    p = 1; 
    k = -1;  
    m = x; 
    i++; 
} 
printf("\ncos(%.2lf) = %lf\n", x, g); 
} 
+2

“它不给我了,因为x的应有的价值。”是一个糟糕的问题陈述。什么是投入,产出和预期产出?它是否适用于0?为什么代码混合'float/double'? - 这只是使分析变得复杂 - 建议只使用“双”。 – chux

+0

提供[MCVE]。请注意'factorial(2 * i)'会为'i> 10'溢出一个64位的'unsigned long long'。 – EOF

回答

1

错误的初始化为m。代码总结了x的奇数次幂,而不是偶数次幂。

// m = x; 
m = 1.0; 

输出

cos(0.00) = 1.000000 
cos(1.05) = 0.500460 // cos(60 degrees) --> 0.5 
cos(1.57) = 0.000796 // cos(90 degrees) --> 0.0 
cos(3.14) = -0.999899 
+0

非常感谢你的时间 –