(C++/JAVA)斐波那契数列

(C++/JAVA)有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子对数为多少?

C++:

#include<iostream>
using namespace std;
int FBNQ(int m){
	if (m == 1 || m == 2)
		return 1;
	else
		return FBNQ(m - 1) + FBNQ(m - 2);
}
int main(){
	int n;
	int p = 1;
	cin >> n;
	while (p <= n){
		cout << FBNQ(p) << "  ";
		p++;
	}
	cout << endl;
}

JAVA:****(略改:输出两行斐波那契数列)

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dm;

import java.util.Scanner;

/**
 *
 * @author Lenovo
 */
public class DM {

    /**
     * @param args the command line arguments
     */
    public static int FBNQ(int m) {
        if (m == 1 || m == 2) {
            return 1;
        } else {
            return FBNQ(m - 1) + FBNQ(m - 2);
        }
    }

    public static void main(String[] args) {
        int a, b;
        int p = 1,q=1;
        Scanner s = new Scanner(System.in);
        a = Integer.parseInt(s.next());
        b = s.nextInt();
        while (p <= a) {
            System.out.print(FBNQ(p)+" ");
            p++;
        }
        System.out.println();
        while (q <= b) {
            System.out.print(FBNQ(q)+" ");
            q++;
        }
    }
}

发布了5 篇原创文章 · 获赞 4 · 访问量 571

猜你喜欢

转载自blog.csdn.net/RY2017_Gaoxusheng/article/details/104187889