#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'(如果有的話)。
您對pi的值是錯誤的 - 使用math.h中的M_PI而不是自旋近似值。 (反正你也需要#include,用於'pow()'等函數)。 –
@PaulR我的學校要求不要使用math.h並使用PI近似值。 :( – CassiusDC
@PaulR:不會'atan(1)* 4'更好嗎?隱式聲明返回'float'的東西真的很差''math.h'在那裏丟失。 –