acm自学Java——Heads / Tails Probability

The probability of n heads in a row tossing a fair coin is 2 −n. Calculate the probability for any positive integer n (1 ≤ n ≤ 1000000).

Input

A list of valid values of n (one per line).

Output

Print a table of n and 2 −n in the following for the given values of n, using the following format: 2^-n = z.xxxe-y where z is a nonzero decimal digit, each x is a decimal digit and each y is a decimal integer with no leading zeros or spaces.

Sample Input

1 100 10000 1000000

Sample Output

2^-1 = 5.000e-1 2^-100 = 7.889e-31 2^-10000 = 5.012e-3011 2^-1000000 = 1.010e-301030

 

用C/C++写是一道水题啦,但是用刚学(还没学)的Java写还是有点麻烦的。

import java.util.*;

import java.math.*;

public class Main {

	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		
		while(sc.hasNext()) {
			int d=sc.nextInt();
			double an=1;
			int t=0;
			
			for(int i=0;i<d;i++) {
				an=an/2.0;
				if(an<1.0) {
					an=an*10.0;
					t++;
				}//end if
				
				
				
				
			}//end for
			BigDecimal a=BigDecimal.valueOf(an);
			a=a.setScale(3, BigDecimal.ROUND_HALF_DOWN);
			System.out.print("2^-"+d+" = ");
			System.out.print(a+"e-"+t+"\n");
		}//end while
		
	}

}

一开始直接用2除,之后格式化输出double型,之后发现会有舍入问题。之后用大数输出,但是发现在精确小数的时候,用ROUND_DOWN不行。之后换做ROUND_HALF_DOWN成功。

之后翻了下别人用C/C++写的代码,发现C/C++都是直接   printf("%.3f",x); 就成功了,要么是C/C++的格式化输出中在确定浮点数的小数的时候就是用ROUND_HALF_DOWN来做的,毕竟没看过C/C++的文档(这种东西谁会看)

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值