非递归方法实现Fibonacci数列

递归有可能发生超限,本文采用循环实现Fibonacci数列

非递归方法实现Fibonacci数列_第1张图片

本例中,input 15,output 2 

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		int n;
		int x,y,tem;
		int before,after;
		while(cin.hasNext()){
			n=cin.nextInt();
			before=0;after=1;
			x=0;y=0;
			for(;n>after;){
				tem=after;
				after+=before;
				before=tem;
			}
			x=n-before;y=after-n;
			System.out.println(x

 

你可能感兴趣的:(非递归方法实现Fibonacci数列)