我正在尝试编写一个基本计算器。我希望我的计算器拥有一个基本算术转换器,当您输入以 10 为基数的整数时,它会给出输出。
我尝试自己编写代码,花了近 3 个小时才弄清楚如何将数字转换为给定的基数,到目前为止它工作得很好,但我遇到了一个问题 - 当我尝试转换时以 2 为底的整数(二进制) 我的计算器不适用于大于 1025 的数字。
我认为问题是因为整数可以容纳最大值或其他东西,所以我尝试了“BigInteger”,但由于它不支持余数“%”操作,我无法使其工作。
else if(c.equals("Base")) {
g = 0;
l = 0;
System.out.println("Enter the number (Integer) you want to convert");
f = scan.nextInt();
System.out.println("Enter the arithmetic base you want for your new number");
m = scan.nextInt();
for (;f>=1;) {
h=f%m;
f=f/m;
k = (int)Math.pow(10,g);
g++;
l =l + (h*k);
}
System.out.println(l);
}
抱歉,如果代码真的很糟糕,并且有更有效的方法,我只是希望它是我的,而不是查找它。
最佳答案
如果你想使用BigInteger
类,你可以使用mod方法而不是“%”。
BigInteger myBigInteger = new BigInteger("943838859");
System.out.println(myBigInteger.mod(BigInteger.TEN));
这将打印 9。
关于Java 整数到二进制转换器代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44693520/