它将打印一系列数,例如1 1 2 3 5 8 13 ....达到给定的数字。请分别使用迭代和递归实现。java

版权声明:大家随便用------------------------------水个文章 https://blog.csdn.net/qq_40182873/article/details/83588548
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class TT {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
	    System.out.print("请输入一个正整数:");
		int n = sc.nextInt();	
		List<Integer> list = new ArrayList<Integer>();
	    if(n == 1) {
	    	list.add(1);
	  	    list.add(1);
		}else if(n<=0){
			System.out.print("输入错误");
			return;
		}else{
			list.add(1);
	  	    list.add(1);
			for (int i = 2;; i++) {
				  if(list.get(i-1) > n) {
					  list.remove(i-1);
					  break;
				  } else {
					  list.add(list.get(i - 1) + list.get(i - 2));
				  }
			}
		}
	    Iterator<Integer> iterator = list.iterator();
	    while (iterator.hasNext()) {
			int j = (int)iterator.next();
			System.out.print(j+" ");
		}
	 }

}





import java.util.Scanner;

public class Demo2 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
	    System.out.print("请输入一个正整数:");
		int n = sc.nextInt();		
		if(n == 1) {
			System.out.print("1 1");
			return;
		}else if(n<=0){
			System.out.print("输入错误");
		}else{
			System.out.print("1 1 ");
			Count(1, 1, n);
		}
	}
	public static void Count(int i,int j,int n) {
			int a = i;
			i = i + j;
			j = a;
			if(i <= n) {
				System.out.print(i+" ");
				Count(i,j,n);
			}
	}

}

猜你喜欢

转载自blog.csdn.net/qq_40182873/article/details/83588548
今日推荐