import javax.swing.*;
public class Fibonacci {
public static void main(String[] args){
String input;
int length;
int term1 = 0;
int term2 = 1;
int temp;
input = JOptionPane.showInputDialog("Enter the number of terms to display");
length = Integer.parseInt(input);
for (int i=0; i<length; i++){
if (i==0)
System.out.print(term1 + ", ");
else {
System.out.print(term2 + ", ");
temp = term1;
term1 = term2;
term2 = term2 + temp;
//System.out.print(term2 + ", ");
}//close else
}//close for
}
}
我最不明白的是 temp = term1;
term1 = term2;
term2 = term2 + temp;
为什么要这样写呢? 这样写有什么好处啊?我自己调试了一下 还是不很明白!
public class Fibonacci {
public static void main(String[] args){
String input;
int length;
int term1 = 0;
int term2 = 1;
int temp;
input = JOptionPane.showInputDialog("Enter the number of terms to display");
length = Integer.parseInt(input);
for (int i=0; i<length; i++){
if (i==0)
System.out.print(term1 + ", ");
else {
System.out.print(term2 + ", ");
temp = term1;
term1 = term2;
term2 = term2 + temp;
//System.out.print(term2 + ", ");
}//close else
}//close for
}
}
我最不明白的是 temp = term1;
term1 = term2;
term2 = term2 + temp;
为什么要这样写呢? 这样写有什么好处啊?我自己调试了一下 还是不很明白!
term1 = term2;
term2 = term2 + temp;
这样写是为了 交换term1和term2的值。
比如:0、1、1、2、3、5、8、13、21、34、55、89、144、233 因此,temp = term1;//temp在此次中循环记录的是N(k)的值
term1 = term2; //term1为下一次循环准备,它会在下一次循环中赋值给temp,使得temp向后移一位
term2 = term2 + temp; //赋值前term2为N(k+1)的值,运算后term2为N(k+2)=N(k+1)+N(k)。下一次循环term2又将成为N(k+1)。
把term2赋给term1,term2的值为原term1与原term2的和。如果用户输入的input为10,程序运行结果为“0, 1, 1, 2, 3, 5, 8, 13, 21, 34,”
通过对赋值语句的循环,实现了第三个数是前两个数的和。另外,程序没有对length = Integer.parseInt(input);
捕捉异常,如果用户输入不是Integer,将会报错。
term1 = term2;
term2 = term2 + temp; 呵呵,先把这个数列的规律摸清楚,就知道为什么这样写了
比如:0、1、1、2、3、5、8、13、21、34、55、89、144、233因此,temp = term1;//temp在此次中循环记录的是N(k)的值
term1 = term2; //term1为下一次循环准备,它会在下一次循环中赋值给temp,使得temp向后移一位
term2 = term2 + temp; //赋值前term2为N(k+1)的值,运算后term2为N(k+2)=N(k+1)+N(k)。下一次循环term2又将成为N(k+1)。