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;
为什么要这样写呢? 这样写有什么好处啊?我自己调试了一下 还是不很明白!
解决方案 »
- 如何停止web服务器中一直在运行的一个线程?
- 转让编程书籍,5折,合肥地区
- String中怎样去除最后一个字符
- java编程思想 第三版 习题讨教做法
- java中抽象方法未重载就使用问题
- 凭心而论,参加像J2EE这样的培训班有没有意思?
- 请问各位大侠:如何在页面中设置,使当不能显示APPLET时候,自动让用户去我们自己的tomcat服务器(局域网内)而不要从sun站点上下载JAVA
- 上传一个指定的文件, 请大家近来看看。 问题能解决, 由发表的都给分!!
- java真的就不能完成这个功能吗?
- 程序编写公示 X*Y*Z+(或-) = 数值;如何用程序解决,提供算法思路也行。
- 我是个java初学都,问大哥大姐们一个有关Canvas问题?
- Java DWG PDF 疑难问题,有人遇见过吗
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)。