运行环境:dev c++ win7
# include <stdio.h>
# include <stdlib.h>
int main ()
{
int f1,f2,f3,x;
f1=1;
f2=2;
printf("输入你想知道值的项\n");
scanf("%d",&x) ;
if(x==1)
{
f3=1;
}
else if (x==2)
{
f3=2;
}
else
{
for(int i=1;i<=x;i++)
{
f3=f1+f2;
f1=f2;//f1一直是第2个数 f2一直都是第3个数
f2=f3;
}
}
printf("%d",f3);
return 0;
}
不明白的是为什么for循环中i要看x的值 也就是输入的项的值
感觉自己好笨啊 是不是真的不适合做程序这块?好多算法都不会 一看就晕 不灰心 也有点灰心了 大牛们给点意见把
这代码明显是根据递归或者数组改出来的,没必要那么麻烦,也不用那么多变量
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 0;
//printf("输入你想知道值的项\n");
//scanf("%d",&x);
int a = 1;
int b = 1;
while (--x >= 0)
{
printf("%d ", a);
b = a + b;
a = b - a;
}
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 0;
printf("输入你想知道值的项\n");
scanf("%d",&x);
int a = 1;
int b = 1;
while (--x >= 0)
{
printf("%d ", a);
b = a + b;
a = b - a;
}
}
理解清楚F(0)=0,F(1)=1,F(n)=F(n-1)+F(n-2)(n≥2,n∈N*)这个递归式,程序就是根据这个递归式而改成的。
x代表是第几个数……从程序中看数列是这样显示的1,2,3,5,8………如果你输入1输出就是1,如果你输入2结果2,如果输入3结果3,4结果为5,依次类推,至于为什要看x的值,因为这里循环是根据第几个数来循环的,这个数列的特点,第三个数等于前两个数的和,所以这段程序貌似有点问题,循环里面i应该从3开始跑
i为什么跟x有关,那你就要注意x表示的含义了(其实相当于数组下标):
x 1 2 3 4 5 6 7 8 9 ……
f3 1 2 3 5 8 13 21 34 55 ……
程序中x是控制循环次数的。
x的值与f3的值一一对应,你要输出x对应的f3的值,自然就是执行x次循环,求得f3的值。
你这个程序中for()语句错了,i=3而不是i=1!