java 小数 转换二进制
答案:1 悬赏:20
解决时间 2021-01-07 15:31
- 提问者网友:伴风望海
- 2021-01-06 20:30
java 小数 转换二进制
最佳答案
- 二级知识专家网友:孤独的牧羊人
- 2021-01-06 21:46
提供思路:
对于 0~1之间的小数,要用二进制表示。以0.725为例,算法如下:
0.725,将其乘以2后得到1。45,取其整数部分1为二进制小数的第一项(十分位),在将小数部分0。45乘2得0。9,取其整数部分为二进制小数的第二位(百分位)0,在将其小数部分0。9乘2,得1。8,取其整数部分为二进制小数的第三位(千分位)1,取其小数部分0。8再乘2……以此类推,直到值为0或形成循环小数则停止。
示例代码:
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
Test t = new Test();
Integer[] result = t.toBin(0.725f);
for(int i : result)
System.out.print(i);
}
public Integer[] toBin(float f) {
if (f >= 1 || f <= 0)
return null;
List list = new ArrayList();
Set set = new HashSet();
int MAX = 8; // 最多8位
int bits = 0;
while (true) {
f = calc(f, set, list);
bits++;
if (f == -1 || bits >= MAX)
break;
}
return (Integer[])list.toArray(new Integer[0]);
}
private float calc(float f, Set set, List list) {
if (f == 0 || set.contains(f))
return -1;
float t = f * 2;
if (t >= 1) {
list.add(1);
return t - 1;
} else {
list.add(0);
return t;
}
}
}
对于 0~1之间的小数,要用二进制表示。以0.725为例,算法如下:
0.725,将其乘以2后得到1。45,取其整数部分1为二进制小数的第一项(十分位),在将小数部分0。45乘2得0。9,取其整数部分为二进制小数的第二位(百分位)0,在将其小数部分0。9乘2,得1。8,取其整数部分为二进制小数的第三位(千分位)1,取其小数部分0。8再乘2……以此类推,直到值为0或形成循环小数则停止。
示例代码:
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
Test t = new Test();
Integer[] result = t.toBin(0.725f);
for(int i : result)
System.out.print(i);
}
public Integer[] toBin(float f) {
if (f >= 1 || f <= 0)
return null;
List
Set
int MAX = 8; // 最多8位
int bits = 0;
while (true) {
f = calc(f, set, list);
bits++;
if (f == -1 || bits >= MAX)
break;
}
return (Integer[])list.toArray(new Integer[0]);
}
private float calc(float f, Set
if (f == 0 || set.contains(f))
return -1;
float t = f * 2;
if (t >= 1) {
list.add(1);
return t - 1;
} else {
list.add(0);
return t;
}
}
}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯