java入门练习题一

这个我在其他博客(http://blog.sina.com.cn/s/blog_8709e3120101hadp.html)看到的习题,作为练手用的。

每天都进步才能“天天向上”

古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....

分析问题:不难发现规律,下个月兔子数量 = 这个月的兔子 + 新出生的兔子,而新出生的兔子=这个月兔子*2,所以可以得出一个公式:

个月兔子数量 =这个月的兔子 + 这个月兔子*2


下面给出java算法:

package com.pratice.daily;

import java.util.Scanner;

public class RabbitBirth {
	public int rabNumber;	
	public int GiveBirthByMonth(int months){
		int newNUM =0;
		int period = months/3;	
		while(period>0){		
			newNUM = rabNumber +  rabNumber*2;
			rabNumber = newNUM;
			period--;
		}		
		return rabNumber;
	}	
	RabbitBirth(){
		this.rabNumber = 2;
	}
	public int getNum(){
		return rabNumber;
	}	
	public static void main(String[] args) {
		RabbitBirth Rab1 = new RabbitBirth();
		int total;
		Scanner scanner = new Scanner(System.in); 
		System.out.println("Initial number of rabbit is: "+Rab1.getNum());
		System.out.println("please input a month:"); 
		int month = Integer.valueOf(scanner.nextLine());
		scanner.close();		
		System.out.print("IN the "+month+"rd month ,");
		total = Rab1.GiveBirthByMonth(month);
		System.out.println("The number of rabbit is: "+total);	

	}

}






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值