【发布时间】:2021-12-14 02:56:43
【问题描述】:
我有一个简单的问题,我如何得到二进制的恭维而不是二进制的常规答案?我有一个执行展位算法的程序,但是当它返回小数时,它给了我一个有点太高的数字,我正在做 9 * -9,它给出的答案是 65455。我只想知道是否有一种获得两个恭维的方法(-81)。我从代码中得到的二进制文件是 1111111110101111,我通过环顾四周知道在找到两者的恭维时等于 -81,我只是不知道如何让我的程序识别或说出来。
编辑:我找到了一个小修复,基本上只是检查产品的二进制文件是否等于我得到的结果,这就是我打印二进制文件并将其转换为十进制的方式,将打印区域作为回答说必须在这里做点什么,我让它正常工作但如果可以的话想清理它
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first number: ");
int operand1 = sc.nextInt();
System.out.print("Enter the second number: ");
int operand2 = sc.nextInt();
String answer = multiply(operand1, operand2);
System.out.println("Final Product (binary): " + answer);
int decimal=Integer.parseInt(answer,2);
if(operand1 * operand2 < 0) {
int decProduct = operand1 * operand2;
String biProduct = toBinary(decProduct, 16);
if (biProduct.length() > 16)
{
biProduct = biProduct.substring(biProduct.length() - 16);
}
if(biProduct.equals(answer)) {
decimal = decProduct;
}
}
System.out.println("Final Answer (decimal): " + decimal);
}
【问题讨论】:
-
当您只有 16 位时,您可以决定其中一位是加号/减号,留下 15 位作为数字,或者您将数字定义为正数并具有全部 16 位。在这种情况下,您不同意 JVM 的处理方式。
标签: java binary twos-complement