# 用C++进行级数计算，帮忙看一下问题出在哪

skynn99 2008-04-14 09:21:23

--------------------------------------------------------------------------------

#include<iostream>
#include<cmath>
using namespace std;
int jc(int m){ //求阶乘
int sum=1;
if(m>=1)
{
for(int k=1;k<=m;k++)
sum*=m;
return sum;
}else return 1;
}

float ts(int n,float x) //求通项
{ float t=pow(-1,n+1)*pow(x,n)/jc(n);
return t;
}

void main()
{int n;
float x,y;
cin>>x;

for(n;ts(n,x)<pow(10,-8);n++)
y+=ts(n,x);
cout<<y<<"\n";
}

...全文
759 15 打赏 收藏 举报

15 条回复

fallening 2008-04-15
• 打赏
• 举报

mathe 2008-04-15
• 打赏
• 举报

WuBill 2008-04-15
• 打赏
• 举报

item =x; //在循环外先取得x
while(fabs(item)>eps){
sum+=item;
item*=-x;
n++; // 个人觉得把n++单写一行比较好,
item/=n; // item/=n++;的值好象和具体编译器有关
}
mathe 2008-04-15
• 打赏
• 举报

mathe 2008-04-15
• 打赏
• 举报

WuBill 2008-04-15
• 打赏
• 举报

[Quote=引用 7 楼 mathe 的回复:]

C/C++ code
double item=1.0;
double sum=0.0;
int n=1;
while(fabs(item)>eps){
sum+=item;
item*=-x;
item/=n++;
}
return sum;
[/Quote]

1+x -x2 /2!+x3/3!-……(-1)n+1xn/n!

1-x +x2/2! -x3/3!+.....
WuBill 2008-04-15
• 打赏
• 举报

#include <iostream>
#include <cmath>
using namespace std;

void main()
{
double x;
double sum,series;
double numerator,denominator;
const double eps = 1e-8;
int flag = 1, n=1;
cin >> x;
numerator = x;
denominator = 1.0;
series=0.0;
sum=1.0;
while (fabs(series-sum)>eps)
{
series=sum;

sum += (flag*numerator / denominator);

n++;
denominator *= n;
numerator *= x;
flag=-flag;
}
cout.precision(16);
cout << series <<"\n";
}
mathe 2008-04-15
• 打赏
• 举报

item/=n改为item/=n++;
mathe 2008-04-15
• 打赏
• 举报

``````
double item=1.0;
double sum=0.0;
int n=1;
while(fabs(item)>eps){
sum+=item;
item*=-x;
item/=n;
}
return sum;
``````
baihacker 2008-04-15
• 打赏
• 举报

``````
//这样好一点点,避免可能影响精度的重复计算
//其中y/fac的计算值得重新思考
//是x/1 * x/2 * x/3 ...的精度高还是y/fac的精度高还是去考虑这里的精度根本就没有意义呢
double x , y;
const double eps = 1e-8;
double c = 1, fac = 1, inc;
int s = 1, n = 1;
cin >> x;
y = x;
while (fabs(inc = s * 1.0 * y / fac)>eps)
{
c += inc;
s = -s;
fac *= ++n;
y *= x;
}``````
baihacker 2008-04-15
• 打赏
• 举报

``````    double x , y;
const double eps = 1e-8;
double l = 0, c = 1, fac = 1;
int s = 1, n = 1;
cin >> x;
y = x;
while (fabs(c-l)>eps)
{
l = c;
c += s * 1.0 * y / fac;
s = -s;
fac *= ++n;
y *= x;
}
cout.precision(16);
cout << c <<"\n"; ``````
WuBill 2008-04-15
• 打赏
• 举报

n *= n+1; //这句问题比较大

Maxwell 2008-04-15
• 打赏
• 举报

WuBill 2008-04-15
• 打赏
• 举报

baihacker 2008-04-14
• 打赏
• 举报

``````
#include <iostream>
#include <cmath>
using namespace std;

void main()
{
double x , y;
const double eps = 1e-8;
double l = 0, c = 1;
int s = 1, n = 1;
cin >> x;
y = x;
while (fabs(c-l)>eps)
{
l = c;
c += s * 1.0 * y / n;
s = -s;
n *= n+1;
y *= x;
}
cout.precision(16);
cout << c <<"\n";
}

``````

6.3w+

C++ 语言相关问题讨论，技术干货分享，前沿动态等
c++ 技术论坛（原bbs）

2008-04-14 09:21

1. 请不要发布与C++技术无关的贴子
2. 请不要发布与技术无关的招聘、广告的帖子
3. 请尽可能的描述清楚你的问题，如果涉及到代码请尽可能的格式化一下