问题:有一头母牛,它从第二年开始每年年初生一头小母牛。每头小母牛从第四个年头开始,每年年初也生一头小母牛。请编程实现在第n年的时候,共有多少头母牛?
package abc; import java.util.Scanner; public class Cattle { public void input() { int n; System.out.println("请输入测试数据组数"); Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); for (int i = 0; i < n; i++) { System.out.println("第" + (i + 1) + "组的母牛数量"); int x = scanner.nextInt(); getcattle(x); } } public void getcattle(int n) { int f1 = 1; int f2 = 2; int f3 = 3; int f4 = 4; if (n < 5) { System.out.println("母牛数为" + n); } else { for (int i = 5; i < n+1; i++) { f1 = f2; f2 = f3; f3 =f4; f4 = f3 + f1; } System.out.println("母牛数为" + f4); } } public static void main(String[] args) { Cattle cattle=new Cattle(); cattle.input(); } } //规律
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)