2016-11-13 91 views
2
#include <stdio.h> 

double pi = 3.141592653589; 
int numberOfTerms = 5; 

int factorial(int n) 
{ 
    if(n > 1) 
     return n * factorial(n - 1); 
    else 
     return 1; 
} 

double DegreesToRadian(double degrees) 
    { 
     return degrees * pi/180; 
    } 

void cosine(double cos){ 
     int x = 0; 
     double ans = 1; 
     int exponent = 2; 
     int isPlus = 0; 
     for(x; x < numberOfTerms - 1; x++){ 
      if(isPlus == 0){ 
       ans -= (pow(cos, exponent))/factorial(exponent); 
       exponent += 2; 
       isPlus = 1; 
      }else{ 
       ans += (pow(cos, exponent))/factorial(exponent); 
       exponent += 2; 
       isPlus = 0; 
      } 
     } 
     printf ("%.12f \t", ans); 
    } 

void sine(double sin){ 
     int x = 0; 
     double ans = sin; 
     int exponent = 3; 
     int isPlus = 0; 
     for(x; x < numberOfTerms - 1; x++){ 
      if(isPlus == 0){ 
       ans -= (pow(sin, exponent))/factorial(exponent); 
       exponent += 2; 
       isPlus = 1; 
      }else{ 
       ans += (pow(sin, exponent))/factorial(exponent); 
       exponent += 2; 
       isPlus = 0; 
      } 
     } 
     printf ("%.12f \n", ans); 
    } 

int main() 
{ 
    double j = -180.00; 
    printf(" "); 
    printf("\n\n"); 

     for (j; j <= 180; j += 5){ 
      printf("%.2f \t", j); 
      printf("%.12f \t", DegreesToRadian(j)); 
      cosine(DegreesToRadian(j)); 
      sine(DegreesToRadian(j)); 
     } 

return 0; 
} 

我使用泰勒级数来查找数字的正弦和余弦,但是当我将numberOfTerms更改为10或15时,它变得不准确(waaaaaaaaayy off),我需要更改哪些数据以使其准确? (是的,我的功能不是最优化的)当我更改numberOfTerms时,为什么我的代码不正确?

我得到一个[Warning]不兼容隐式声明内置函数'pow'(如果有的话)。

+0

您对pi的值是错误的 - 使用math.h中的M_PI而不是自旋近似值。 (反正你也需要#include ,用于'pow()'等函数)。 –

+0

@PaulR我的学校要求不要使用math.h并使用PI近似值。 :( – CassiusDC

+0

@PaulR:不会'atan(1)* 4'更好吗?隐式声明返回'float'的东西真的很差''math.h'在那里丢失。 –

回答

1

让我们假设您保留numberOfTerms的值为10。然后,在cosinesine函数中,在for循环中,您每次都将exponent增加2。而且,分母中使用的因子是exponent

如果循环运行9次,则exponent的值将增加为2, 4, 6, 8, 10, 12, 14, 16, 18

我们知道14! = 87178291200。但signed int(用于返回阶乘函数的结果)可以保持正值,最大值为2147483647。发生溢出。

我建议你使用double(或甚至unsigned long long)作为返回类型和阶乘函数的参数。但不要尝试计算大数的阶乘,因为它们不适合C中的任何数据类型。

此外,由于您自己没有定义pow函数,所以我认为您错过了顶部的#include<math.h>

另一个建议,将pi定义为符号常量而不是全局变量。

+0

非常感谢!你是一个救星花花公子。我完全忘记了具有这些限制的整数。 – CassiusDC

0

pow隐式声明返回一个int,但实际的定义返回双,代码会解释双倍的通过导致的完全不正确的值位模式为int - 不仅仅是双的整数部分。

相关问题