我尝试实现一个玩具脚本,用于将小数(以下示例中的输入为 0.21)转换为二进制数字 - 一切正常,除了我不知道如何防止的数字错误:
bin_dec <- function() {
b <- as.numeric(readline("Input Binary digit: "))
dec=9999999
P=9999999
N=b
print("N B P U")
while (dec != b & P != 0) {
P = N*2
U = floor(P)
dec = P%%1
print(sprintf("%s 2 %s %s", N, P, U))
N = dec
}
}
> bin_dec()
Input Binary digit: 0.21
[1] "N B P U"
[1] "0.21 2 0.42 0"
[1] "0.42 2 0.84 0"
[1] "0.84 2 1.68 1"
[1] "0.68 2 1.36 1"
[1] "0.36 2 0.72 0"
[1] "0.72 2 1.44 1"
[1] "0.440000000000000 2 0.879999999999999 0"
[1] "0.879999999999999 2 1.76000000000000 1"
[1] "0.759999999999998 2 1.52000000000000 1"
[1] "0.519999999999996 2 1.03999999999999 1"
[1] "0.039999999999992 2 0.079999999999984 0"
[1] "0.079999999999984 2 0.159999999999968 0"
[1] "0.159999999999968 2 0.319999999999936 0"
[1] "0.319999999999936 2 0.639999999999873 0"
[1] "0.639999999999873 2 1.27999999999975 1"
[1] "0.279999999999745 2 0.559999999999491 0"
[1] "0.559999999999491 2 1.11999999999898 1"
[1] "0.119999999998981 2 0.239999999997963 0"
[1] "0.239999999997963 2 0.479999999995925 0"
[1] "0.479999999995925 2 0.95999999999185 0"
[1] "0.95999999999185 2 1.9199999999837 1"
[1] "0.919999999983702 2 1.83999999996740 1"
[1] "0.839999999967404 2 1.67999999993481 1"
[1] "0.679999999934807 2 1.35999999986961 1"
[1] "0.359999999869615 2 0.71999999973923 0"
[1] "0.71999999973923 2 1.43999999947846 1"
[1] "0.439999999478459 2 0.879999998956919 0"
[1] "0.879999998956919 2 1.75999999791384 1"
[1] "0.759999997913837 2 1.51999999582767 1"
[1] "0.519999995827675 2 1.03999999165535 1"
[1] "0.0399999916553497 2 0.0799999833106995 0"
[1] "0.0799999833106995 2 0.159999966621399 0"
[1] "0.159999966621399 2 0.319999933242798 0"
[1] "0.319999933242798 2 0.639999866485596 0"
[1] "0.639999866485596 2 1.27999973297119 1"
[1] "0.279999732971191 2 0.559999465942383 0"
[1] "0.559999465942383 2 1.11999893188477 1"
[1] "0.119998931884766 2 0.239997863769531 0"
[1] "0.239997863769531 2 0.479995727539062 0"
[1] "0.479995727539062 2 0.959991455078125 0"
[1] "0.959991455078125 2 1.91998291015625 1"
[1] "0.91998291015625 2 1.8399658203125 1"
[1] "0.8399658203125 2 1.679931640625 1"
[1] "0.679931640625 2 1.35986328125 1"
[1] "0.35986328125 2 0.7197265625 0"
[1] "0.7197265625 2 1.439453125 1"
[1] "0.439453125 2 0.87890625 0"
[1] "0.87890625 2 1.7578125 1"
[1] "0.7578125 2 1.515625 1"
[1] "0.515625 2 1.03125 1"
[1] "0.03125 2 0.0625 0"
[1] "0.0625 2 0.125 0"
[1] "0.125 2 0.25 0"
[1] "0.25 2 0.5 0"
[1] "0.5 2 1 1"
[1] "0 2 0 0"
> sessionInfo()
R version 2.7.2 (2008-08-25)
i386-pc-mingw32