好的,我正在进行一个程序,我试图使右侧的结果与左侧相等,精确到0.0001%
正弦x = x - (x ^ 3) / 3!+(x ^ 5)/ 5!+(x ^ 7)/ 7!+ ....
#include<iostream>
#include<iomanip>
#include<math.h>
using namespace std;
long int fact(long int n)
{
if(n == 1 || n == 0)
return 1;
else
return n*fact(n-1);
}
int main()
{
int n = 1, counts=0; //for sin
cout << "Enter value for sin" << endl;
long double x,value,next = 0,accuracy = 0.0001;
cin >> x;
value = sin(x);
do
{
if(counts%2 == 0)
next = next + (pow(x,n)/fact(n));
else
next = next - (pow(x,n)/fact(n));
counts++;
n = n+2;
} while((fabs(next - value))> 0);
cout << "The value of sin " << x << " is " << next << endl;
}
假设我输入了 x 的值为 45
我得到的结果是
sin 45 的值为 NaN(非数值)。
有没有人能帮我看看我哪里错了?
long
的范围,因此您的fact
函数无法返回正确的答案。 - Alan Stokesnext
的连续值吗?这样或许能更容易看出问题出在哪里。 - Alan Stokes