求分数序列
2/1 +3/2+5/3+8/5+13/8+21/13...
前20项之和。
我这样的代码为什么不对啊?输出是21.00000000 答案输出是32.6602607986
#include <stdio.h>
int main()
{
int fenzi(int n);
int fenmu(int m);
int i;
float s=0,tem;
for(i=1;i<=20;i++)
{
tem=fenzi(i)/fenmu(i);
s=s+tem;
}
printf("%f",s);
return 0;
}
int fenzi(int n)
{
if(n==1) return 2;
else if(n==2) return 3;
else return (fenzi(n-2)+fenzi(n-1));
}
int fenmu(int m)
{
if(m==1) return 1;
else if(m==2) return 2;
else return (fenmu(m-2)+fenmu(m-1));
}
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int fenzi(int n);
int fenmu(int m);
int main()
{
int i;
float s = 0, tem;
for (i = 1; i <= 20; i++)
{
tem = (double)fenzi(i) / (double)fenmu(i);
s = s + tem;
}
printf("%f", s);
return 0;
}
int fenzi(int n)
{
if (n == 1) return 2;
else if (n == 2) return 3;
else return (fenzi(n - 2) + fenzi(n - 1));
}
int fenmu(int m)
{
if (m == 1) return 1;
else if (m == 2) return 2;
else return (fenmu(m - 2) + fenmu(m - 1));
}
你都用int当然不对,要用float double
32.660263Press any key to continue . . .
楼主所有想输出float的地方都被省略成int了,重新看一下关于float的说明