例3. 请编制一函数fun(),其功能是:根据以下公式计算s,计算结果作为数值返回,n通过行参传人。
s=1/(1×2)+1/(2×3)+…+ 1/(n×(n+1))
例如:若n=10则s值为0.909091。
试题程序:(同例2)
#include <conio.h>
#include <stdio.h>
#include <string.h>
double fun(int n)
{
}
main()
{
int n;
double s;
clrscr();
printf("/n/nInput n:");
scanf("%d",&n);
s=fun(n);
printf("/n/nThe s=%f/n/n",s);
}
参考答案:(注意有一处错误)
double fun(int n)
{
int i;
double s=0.0,t=0.0;
for(i=1;i<=n;i++)
{
/***There is a error in here***/
t=1/(i*(i+1));
/************End***************/
s+=t;
}
return s;
}
例4. 请编制一函数fun(),其功能是:根据以下公式计算s,计算结果作为数值返回,n通过行参传人。
s=1+X+X2/2!+X3/3!+…+ Xn/n!
例如:若n=10;X=0.3则s值为1.349859。
试题程序:
#include <conio.h>
#include <stdio.h>
#include <string.h>
double fun(double x,int n)
{
}
main()
{
int n;
double x,s;
clrscr();
printf("/n/nInput n:");
scanf("%d",&n);
printf("/n/nInput X:");
scanf("%lf",&x);
s=fun(x,n);
printf("/n/nThe s=%f/n/n",s);
}
参考答案:
double fun(double x,int n)
{
int I,j,t=1;
double s=0.0,p=0.0;
for(i=1;i<=n;i++)
{
|
|
t=1; for(j=1;j<=i;j++) { t=t*j; } | /*等价于 t*=i; */ |
p=p*t;
s=s+p/t;
}
return s;
}
还有记住X0.5=√X(开X的平方)。