題目:
輸入任意一個(gè)0-1之間的浮點(diǎn)數(shù),轉(zhuǎn)為2進(jìn)制數(shù)
如果小數(shù)點(diǎn)后32位無(wú)法精確表示 則輸出 ERROR
小數(shù)點(diǎn)后用二進(jìn)制表示為,右移2? 即0.5 二進(jìn)制表示 0.1,0.25表示0.01
0.625 即為 0.101
兩個(gè)樣例:
輸入:
0.625? ? ?或? ? ?0.3
輸出:
0.101? ? ? 或? ? ?ERROR
tip:
已知十進(jìn)制整數(shù) 轉(zhuǎn)為二進(jìn)制數(shù),除二取余??梢运伎际M(jìn)制小數(shù)可以乘2取整,
即每次乘2,如果大于1則在當(dāng)前小數(shù)點(diǎn)后位進(jìn)1,直到取整后為0.
演示過(guò)程:?
0.625*2
1.25 -- 0.1
?0.25*2
0.5? -- 0.10
?0.5*2
1.0 -- 0.101
結(jié)果 0.101
(Java代碼如下)
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double n = sc.nextDouble();
//字符串拼接
StringBuilder sb = new StringBuilder("0.");
while(n > 0) {
n *= 2;
if(n >= 1) {
sb.append("1");
n--;
}else {
sb.append("0");
}
if(sb.length() > 34) {//32+2
System.out.println("ERROR");
return;
}
}
System.out.println(sb.toString());
}