问题1:用递归调用计算1/2+2/3+3/4...+n/(n+1),哪里错了呢?
代码如下:
正确的代码是这样子:
问题2:编程计算f(x) = 1+x+x^2+x^3+...+x^n,要求最后一项的精度为0.0001. (-1<x<1),怎么弄呢?
回答2:
补充:1<x<1,这个是程序的输入条件,可以不在程序中体现,也就是在测试输入时,输入的数据在-1到1之间。
疑问:n是未知的,那怎么求结果?
补充:这个是较简单的C程序,用的是C的基本结构和函数,你的n是未知的,而结束的条件是当X^n<0.0001时,所以n的值是在计算中得到的而不是预先设定的。
代码如下:
#include<iostream>
using namespace std;
double fun(int n)
{
double s;
if(n=0)
s=0;
else
s=fun(n-1)+n/(n+1);
return s;
}
void main()
{
int n;
cin>>n;
cout<<fun(n);
}
正确的代码是这样子:
#include<iostream>
using namespace std;
double fun(int n)
{
int m=1;
if(n == m)
return n / (n + 1.0);
else
return fun(n - 1) + n / (n + 1.0); //用1.0而不是1,转换,否则结果为0
}
int main()
{
int n;
cin >> n;
cout << fun(n);
return 0;
}
问题2:编程计算f(x) = 1+x+x^2+x^3+...+x^n,要求最后一项的精度为0.0001. (-1<x<1),怎么弄呢?
回答2:
#include <stdio.h>
#include <math.h>
int main()
{
int i=0;
double s=0,ds,x;
scanf("%lf",&x);
do {
ds=pow(x,i);
s+=ds;
i++;
} while(abs(ds)>0.0001);
printf("%lf\n",s);
return 0;
}
补充:1<x<1,这个是程序的输入条件,可以不在程序中体现,也就是在测试输入时,输入的数据在-1到1之间。
疑问:n是未知的,那怎么求结果?
补充:这个是较简单的C程序,用的是C的基本结构和函数,你的n是未知的,而结束的条件是当X^n<0.0001时,所以n的值是在计算中得到的而不是预先设定的。