直接上代码
#include <iostream>
#include <cmath>//Math库用于对比运算结果
using namespace std;
double MySin(double x, double r);
int main(void)
{
double x;
cout.precision(12);
cout << "输入一个数,求其正弦(将显示12个有效数字):";
cin >> x;
cout << "Ansters(精度 3位) = " << MySin(x, 1e-3) << endl;
cout << "Ansters(精度 4位) = " << MySin(x, 1e-4) << endl;
cout << "Ansters(精度 5位) = " << MySin(x, 1e-5) << endl;
cout << "Ansters(精度 6位) = " << MySin(x, 1e-6) << endl;
cout << "Ansters(精度 7位) = " << MySin(x, 1e-7) << endl;
cout << "Ansters(使用库) = " << sin(x) << endl;//只是对比验证用
system("pause");
return 0;
}
double Exponentiation(double x, int y);
int factorial(int i);
double MySin(double x, double r)//自定义求正弦的函数,r误差
{
double ans = 0, i = 0;
int n = 1, s = -1;
do {
ans += (s == 1 ? s = -1 : s = 1) * (i = (Exponentiation(x, n) / factorial(n)));
n += 2;
} while (r < i);
return ans;
}
double Exponentiation(double x, int y)//计算x的y(整数)次幂
{
double ans = 1;
if (y == 0)
return 1;
while (y >= 1)
{
ans *= x;
y--;
}
return ans;
}
int factorial(int i)//计算正整数的阶乘,递归方法
{
if (i >= 1)
return i * factorial(i - 1);
else
return 1;
}