代码之家  ›  专栏  ›  技术社区  ›  Einstein118

为什么这只返回值1和0?

  •  -2
  • Einstein118  · 技术社区  · 10 年前

    我已经尝试编辑了几次了,在我看来,我没有发现任何错误。。。 最初的问题是输入一个索引编号,然后在该索引处找到fibbonaci编号。。。 程序现在看起来很好,但对于前两个值,返回1,然后返回1,同样返回0。 我能做什么?

    代码:

    import java.util.Scanner;
    public class main2 {
    
        public int FibIterative(int i){
            System.out.print.ln("Enter the index of the series.");
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();            
            if (n<0){
                throw new IllegalArgumentException("No number in the series is negative");
            } else if (n==0||n==1) {
                return n;
            }
            int prev=0;
            int prevPrev=1;
            int current=0
            for (int x=0; x<n; x++){
                current= prev+ prevPrev;
                prevPrev= prev;
                prev= current;
            }
            return current;
        }
    }
    
    1 回复  |  直到 10 年前
        1
  •  1
  •   rahul    10 年前

    尝试此代码:)

        int p=0;
        int c=1;
        int sum=0;
        String fibo="";
    
        for(int i=0;i<10;i++)
            {
                sum =c+p;
                //System.out.println(sum);
                p=c;
                c=sum;
                fibo=fibo+sum;
    
            }
            return fibo;