java50题----10小球落地

<pre name="code" class="java">/*
一球从100米的高度自由落下,每次落地后反跳回原高度的一半,再落下。
求它在第10次落地时,共经过多少米?第10次反弹多高?

*/


import java.io.*;

class Demo
{
	private Demo(){}

	private static Demo instance = new Demo();

	public void getResults(int n)
	{
		final double H = 100;
		double sum = H;
		//h 是此次弹起了的高度
		double h = H/2;			
	//从第2次开始进入循环,第1次直接输出初始化值。	
		for(int i = 2; i <= n ; i++)
		{
			//当前弹起了的高度*2 +上一次的sum就是本次一共经过的路程。
			sum = sum + h*2;
			//h 的值变成了下一次能弹起来的高度
			h = h/2;

		}

		System.out.println(n+"次撞地时走过的路程:"+sum+"\n"+n+"次撞地后能弹起来的高度:"+h);

	}

	public static Demo getInstance()
	{
		return instance;

	}

}

class MainClass 
{
	public static void main(String[] args) throws Exception
	{
		Demo d = Demo.getInstance();
		
		BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));

		String reg = "[1-9]+\\d*";

		String str = null;

		int n = 0;

		System.out.println("输入一个1到N的数字:");

		for(str = buf.readLine().trim();true; str = buf.readLine().trim())
		{
			if(str.isEmpty() == true)
				continue;

			if(str.equals("quit") == true)
				System.exit(0);

			if(str.matches(reg) == true)
			{
				n = Integer.parseInt(str);
				
				d.getResults(n);
			}
			else
			{
				System.out.println("非法数字!输入一个1到N的数字:");
			}


		}
	}
}



/*




*/



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值