2016-11-13 89 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 - 不僅僅是雙的整數部分。

相關問題