我必须实现我自己的版本的double cos(double x)
函数,它存在于C的<math.h>
库中.
关于这个函数的实现,我有一些不理解的地方.
原则上,我必须
接收用户输入(例如,double x
),在该double x
上实现余弦的泰勒级数.并返回一个双精度数.
我需要将我的实现与内置的double cos(double x)
进行比较,并将其打印出来.
我的函数需要精确到1.0e-6的水平(这是100万分之一,小数点后7位)
我似乎对这样的实施缺乏基本的了解,因为我在这里偶然发现了许多问题.
我的用户输入是incorrect.我应用了一个双精度数字,它不仅打印出wrong number,而且每次都打印出random数字.
我用余弦的泰勒级数计算余弦值的方法也可能是不正确的.
built-in double cos(double x)
功能每次都有the same behavior、打印wrong numbers和random号码.
我已经使用了GCC编译器,并编译了以下行的文件:
gcc -ansi -Wall -pedantic my_cos.c -lm
As you can, every thing about those results is just... wrong:
以下是我的my_Cos.h文件:
#define PI 3.1415926535
double my_cos(double);
以下是我的my_Cos.c文件:
#include <stdio.h>
#include <math.h>
#include "my_cos.h"
double my_cos(double x)
{
double cos = 1 - ((pow(x,2))/(2)) + ((pow(x,4))/(24)) - ((pow(x,6))/(1*2*3*4*5*6)) + ((pow(x,8))/(1*2*3*4*5*6*7*8)) - ((pow(x,10))/(1*2*3*4*5*6*7*8*9*10));
return cos * ((PI)/(180));
}
int main()
{
double x;
printf("Please insert a number:");
scanf("%f", &x);
printf("Your number is: %f\n", x);
printf("using my function:");
printf("%.7f\n", my_cos(x));
printf("Using C's function:");
printf("%f\n", cos(x));
return 0;
}
这条长队double cos = 1 - ((pow(x,2))/(2)) + ((pow(x,4))/(24)) - ((pow(x,6))/(1*2*3*4*5*6)) + ((pow(x,8))/(1*2*3*4*5*6*7*8)) - ((pow(x,10))/(1*2*3*4*5*6*7*8*9*10));
is an implementation of the Taylor series of a cosine:个
第return cos * ((PI)/(180));
行应该是a conversion from the degrees form to the radian form,因为内置函数还返回以弧度为单位的参数的余弦.
我非常希望得到关于如何解决这些问题和改进我的计划的建议.