c语言数列求和 2/1+3/2+5/3+8/5………求前n项之和
发布网友
发布时间:2024-10-23 23:57
我来回答
共2个回答
热心网友
时间:2024-10-27 14:51
#include<stdio.h>
float sum (n) {
float sum = 0;
int i = 1;
for(; i <= n; i++) {
sum += ((float)i)/(i+1);
}
return sum;
}
main()
{
printf("%.2f\n", sum(20));
}
热心网友
时间:2024-10-27 14:52
#include "stdio.h"
int main(void){
int n,i,a,b;
double sum;
while(1){
printf("Input n(int n>0)...\nn=");
if(scanf("%d",&n) && n>0)
break;
printf("Error, must n>0: ");
}
for(sum=0.0,a=1,b=2,i=1;i<=n;i++){
sum+=b/(a+0.0);
b+=a;
a=b-a;
}
printf("The result is %g\n",sum);
return 0;
}