哪位高手帮我解释一下这个是做了一个什么事?

candy898 2009-12-07 07:30:53
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;
为什么要这样写呢? 这样写有什么好处啊?我自己调试了一下 还是不很明白!
...全文
123 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
苍蝇①号 2009-12-07
  • 打赏
  • 举报
回复
斐波那契数列的特点是:从第3个元素开始,每个元素都是前面紧挨的两个元素之和。N(k+2)=N(k+1)+N(k)(k>=0)
比如: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)。
whut0802 2009-12-07
  • 打赏
  • 举报
回复
temp = term1;
term1 = term2;
term2 = term2 + temp;

呵呵,先把这个数列的规律摸清楚,就知道为什么这样写了
justinavril 2009-12-07
  • 打赏
  • 举报
回复
不是这么写有啥好处的问题 是这个数列的特点就是这样 从第4项开始(第1项是0),每一项是前两项的和。
daisyp 2009-12-07
  • 打赏
  • 举报
回复
[Quote=引用楼主 candy898 的回复:]
我最不明白的是  temp = term1;
term1 = term2;
term2 = term2 + temp;
为什么要这样写呢? 这样写有什么好处啊?我自己调试了一下 还是不很明白!
[/Quote]
如果单单是看楼主贴出来的这部分代码,只能看到赋值语句而已。
把term2赋给term1,term2的值为原term1与原term2的和。

如果用户输入的input为10,程序运行结果为“0, 1, 1, 2, 3, 5, 8, 13, 21, 34,”
通过对赋值语句的循环,实现了第三个数是前两个数的和。

另外,程序没有对
length = Integer.parseInt(input); 
捕捉异常,如果用户输入不是Integer,将会报错。
heartraid86 2009-12-07
  • 打赏
  • 举报
回复
斐波那契数列的特点是:从第3个元素开始,每个元素都是前面紧挨的两个元素之和。N(k+2)=N(k+1)+N(k)(k>=0)
比如: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)。

999朵玫瑰 2009-12-07
  • 打赏
  • 举报
回复
input = JOptionPane.showInputDialog("Enter the number of terms to display");
lodachi 2009-12-07
  • 打赏
  • 举报
回复
一楼看错了吧
JavaAlpha 2009-12-07
  • 打赏
  • 举报
回复
temp = term1;
term1 = term2;
term2 = term2 + temp;


这样写是为了 交换term1和term2的值。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧