Fibonnaci序列解释

时间:2016-03-15 23:07:08

标签: java

有人可以向我解释一下这部分代码:

public static void sequence(int nterms){ 
     int num1 = 0; 
     int num2 = 1; 
     int num = 2;  

     if (nterms <= 0){ 
      System.out.println("Enter a positive integer"); 

     } 
     else if (nterms == 1){ 
      System.out.println(" fibonacci sequence: " + num1);
     }
     else{ 
      System.out.println(num1 ); 
      System.out.println(num2);

      while (num < nterms){ 
       int nth = num1 + num2; 
       System.out.println(nth); 
       num1 = num2;  
       num2 = nth; 
       num++;
      }
     }
    }

输出中的数字序列是正确的。所以代码有效。但是为什么你最后会做num ++呢?我知道nth是前两个数字加在一起,但为什么你nterms == 1并打印&#34;&#34; + NUM1?我不明白。

1 个答案:

答案 0 :(得分:0)

这是

 public static void sequence(int nterms){ 
     /*instancation of needed variables : nth = num1+numb2 later in the code*/
     int num1 = 0; 
     int num2 = 1; 
     /*num is the number of term you've encoutered, as the first two are in
     the initialization, you start at 2*/
     int num = 2;  

     if (nterms <= 0){ //check wether the function has a correct input or not*/
      System.out.println("Enter a positive integer"); 

     } 
     else if (nterms == 1){ /*if it's the first term we know in num1*/
      System.out.println(" fibonacci sequence: " + num1);
     }
     else{ 
      System.out.println(num1);/*we print the first two terms*/ 
      System.out.println(num2);

      while (num < nterms){ /*we loop till we reached the wanted number*/
       /*we know a term is equal to the two terms before it, at least I hope you do*/
       int nth = num1 + num2; 
       System.out.println(nth); /*we've got our number so we print it*/
       num1 = num2;  /*we make sure num1 and num2 are the last two encountered, so num1 becomre num2 and num2 become the current term (nth)*/
       num2 = nth; 
       num++;/*we increment the variable as we've met printed a new term*/
      }
     }
    }