该自定义sin函数限制输入内容为-6-6的整数,输入数据不合格后有三次输入机会,且计算三项,可根据需求进行对函数修改。
计算结果会与math库sin函数对比。
#include<iostream>
#include<math.h>
using namespace std;
double my_sin(int);
int my_factorial(int);
double myNth_power(double,int);
int my_skip(int);
int main()
{
int x;
double y;
cout<<"Please enter an integer[-6,6]:"<<endl;
for (int i=0;i<3;i++)
{
cin>>x;
switch (i)
{
case 0:
cout<<"The number must be between - 6 and 6.You just have "<<2-i<<" chances"<<endl;
break;
case 1:
cout<<"The number must be between - 6 and 6.You just have "<<2-i<<" chance"<<endl;
break;
case 2:
cout<<"Wrong!Wrong!Wrong! Go away!"<<endl;
break;
}
if(x>=-6&&x<=6)
{
y=sin(x);
cout<<endl<<"Using the MATH library"<<endl<<"sin("<<x<<")="<<y<<endl<<endl;
cout<<"Custom functions based on Taylor Formula"<<endl<<"mysin("<<my_sin(x)<<")="<<y<<endl;
cout<<endl<<"Victory!";
break;
}
else
{
cout<<"The number is not qualified!"<<endl;
}
}
return 0;
}
double my_sin(int x) //sin(x)
{
double y;
int m=1;
for(int i=0;i<=3;i++)
{
y+=myNth_power(x,i)*my_skip(i)/my_factorial(i);
}
return y;
}
int my_factorial(int n) //n!
{
int y=1;
int i;
if(n=0)
{
return 1;
}
else
{
for(i=1;i<=n;i++)
{
y*=i;
}
return y;
}
}
double myNth_power(double x,int n) //x^n
{
double y;
for(int i=1;i<=n;i++)
{
y*=x;
}
return y;
}
int my_skip(int x) //010101...
{
if(x%2==0){return 0;}
else{return 1;}
}
欢迎大家指正。