有一个分数序列,想用double型变量存储结果,请问哪里出问题?

有一个分数序列,2/1, 3/2, 5/3, 8/5, 13/8, 21/13……先观察数列规律,再求出数列的前n项之和,用double型变量存储结果,哪里有问题?
#include<stdio.h>
main()
{
int a=1,b=2,n,i=1,r;
double sum=0,x;
printf("Please input an integer:");
scanf("%d",&n);
while(i<=n)
{ x=b/a;
sum=sum+x;
r=a+b;
a=b;
b=r;
i++;
}
printf("The result is %lf",sum);
return 0;
}

梦里花落0921
浏览 126回答 1
1回答

MYYA

#include<stdio.h>main(){&nbsp;int&nbsp;a=1,n,i=1,r;&nbsp;double&nbsp;sum=0,b=2,x;&nbsp;printf("Please&nbsp;input&nbsp;an&nbsp;integer:");&nbsp;scanf("%d",&n);&nbsp;while(i<=n){&nbsp;&nbsp;&nbsp;x=b/a;//这里你原来是2/1,结果是2,是int型,所以我把b也换了。&nbsp;sum=sum+x;&nbsp;r=a+b;&nbsp;&nbsp;a=b;&nbsp;b=r;&nbsp;i++;}&nbsp;printf("The&nbsp;result&nbsp;is&nbsp;%lf",sum);&nbsp;return&nbsp;0;}
打开App,查看更多内容
随时随地看视频慕课网APP