#include
using namespace std;
int main()
{
double f(double x);
double s, k;
cout<<"Please enter an mumber: s = ";
cin>>s;
cout<<endl;
k = f(s);
cout<<"The result is "<<k<<endl;
return 0;
}
//求解幂函数
double power(double m, int n)
{
double p = 1.0;
for(int i = 1; i <= n; i ++)
p *= m;
return p;
}
//求解阶乘
int factorial(int g)
{
int a = 1, i;
if (g == 0)
a = 1;
if (g > 0)
for(i = 1; i <= g; i++)
a *= i;
return a;
}
double f(double x)
{
int factorial(int g);
double power(double m, int n);
double y = 0.0;
int i = 1;
do
{
y = (i % 4 == 1) ? y + (power(x, i)/factorial(i)) : y - (power(x, i)/factorial(i));
i += 2;
}while((power(x, i) / factorial(i)) >= 1e-10);
return y;
}
The result is -1.26779
Press any key to continue
修改处见注释,供参考:
#include <iostream>
using namespace std;
int main()
{
double f(double x);
double s, k;
cout << "Please enter an mumber: s = ";
cin >> s;
cout << endl;
k = f(s);
cout << "The result is " << k << endl;
return 0;
}
//求解幂函数
double power(double m, int n)
{
double p = 1.0;
for (int i = 1; i <= n; i++)
p *= m;
return p;
}
//求解阶乘
double factorial(int g) // 修改
{
int i;
double a = 1; // 修改
if (g == 0)
a = 1;
if (g > 0)
for (i = 1; i <= g; i++)
a *= i;
return a; // 修改
}
double f(double x)
{
double factorial(int g); // 修改
double power(double m, int n);
double y = 0.0;
int i = 1, sign = 1; // 修改
while ((power(x, i) / factorial(i)) >= 1e-10) { // 修改
y = (sign > 0) ? y + (power(x, i) / factorial(i)) : y - (power(x, i) / factorial(i));
i += 2;
sign = -sign; // 修改
}
return y;
}