注册 登录
编程论坛 JAVA论坛

斐波那契数列,求大神看看

后卿 发布于 2016-12-18 21:05, 1975 次点击
只有本站会员才能查看附件,请 登录
只有本站会员才能查看附件,请 登录

题目是           编程生成斐波纳契数列。 前两个数应为0和1,而最后一个数应为89。
                 提示: 斐波纳契数列是0、1、1、2、3、5、8、13、… 89。除了前两个数值0和1,序列中的每个数值是前两个之和。
不知道哪里编译错了,请大神们看看
12 回复
#2
yangnew2016-12-18 21:51
这个问题出的有点大吧,你那些a,b,c的初始定义都不在while循环外,怎么可能正确
#3
后卿2016-12-18 22:08
回复 2楼 yangnew
为什么不能在while内呢
#4
GrayJerry2016-12-19 09:07
程序从上到下运行,到while(c<89)时,之前并没有定义c这个变量,所以会报错,所有的变量都是:先声明、然后赋值、最后使用变量
#5
GrayJerry2016-12-19 09:17
具体代码如下:
public class While1 {
   
    public static void main(String[] args) {
        int a = 0;
        int b = 1;
        int c = 1;
        StringBuilder result = new StringBuilder();
        while(c < 89) {
            c = a + b;
            if(c == 1) {
                //如果c是第三位的值,把a,b的加到result中
                result.append(a);
                result.append(" ");
                result.append(b);
                result.append(" ");
            }
            result.append(c);
            result.append(" ");
            //b的值付给a
            a = b;
            //c的值付给b
            b = c;
        }
        System.out.println(result.toString());
    }

}
#6
后卿2016-12-19 13:26
回复 5楼 GrayJerry
看到了,谢谢
#7
后卿2016-12-19 13:33
回复 5楼 GrayJerry
只有本站会员才能查看附件,请 登录
只有本站会员才能查看附件,请 登录
那为什么我在前面定义了C的值还是有错呢
而且按照你的程序编译 的时候,会有这样的错误?(第一张)

[此贴子已经被作者于2016-12-19 13:35编辑过]

#8
后卿2016-12-19 13:53
回复 5楼 GrayJerry
只有本站会员才能查看附件,请 登录
那个我编出来了,不过你的实在太复杂了
#9
后卿2016-12-19 14:28
回复 5楼 GrayJerry
高手,你的完全正确。。。。
#10
lijun5202016-12-21 16:04
#11
cailiaop2016-12-21 21:57
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 斐波那契数列
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 0;
            int b = 1;
            int c=0;
            while(c<89)
            {
                c = a + b;
                a = c ;
                b = a-b;
                Console.WriteLine(c);
            }
            Console.ReadLine();  
        }
    }
}
#12
绿蜡成新妆2016-12-27 10:47
//这是我用While循环实现的,楼主可以细细体会下,我建议楼主再试试用递归的方法来实现这个程序。
//编写程序输出斐波那契数列,前两个数是0,1 ,最后一个数为89
public class FabWhile{
    public static void main (String [] args){
        int f = 0;
        int f1 = 0;
        int f2 = 1;
        System.out.print(f1+" "+f2+" ");
        while(f<89){
            f = f1 + f2;
            f1 = f2;
            f2 = f;
            System.out.print(f+" ");            
        }
    }
}
#13
绿蜡成新妆2016-12-27 11:09
楼主,在while循环里赋初值,那每一次循环a和b都会变为0和1,后面的运算就完全没有意义
1