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++的文档(这种东西谁会看)。