以下是作业要求的描述:
在本实验中,您将输入两个以十为基数的数字并将它们转换为二进制。然后,您将以二进制形式添加这些数字并打印出结果。 输入的所有数字都在 0 到 255 之间(含 0 和 255),并且二进制输出仅限于 8 位。这意味着两个相加数的和也将被限制为 8 位。如果两个数字之和超过 8 位,请打印总和的前 8 位数字以及消息“Error: Overflow”。 您的程序应该使用整数数组来表示二进制数,个位 (2^0) 存储在索引 0 处,两位数 (2^1) 存储在索引 1 处,一直到 2^7 处存储在索引处7. 你的程序应该包含以下方法: int[] ConvertToBinary(int b)将参数转换为二进制值并将其存储为整数数组返回。 void printBin(int b[]) 将数组中存储的二进制数输出一行。请注意,每个输出 0 或 1 之间应该正好有一个空格。 int[] addBin(int a[], int b[])将数组中存储的两个二进制数相加,并在新的整数数组中返回总和。
当将我的代码输入 CodeRunner(它测试代码并根据每个测试的结果返回成绩)时,我似乎无法通过其中一项测试。这是我收到的消息:
*您正确通过了 44 项测试中的 43 项。 您的得分为 97%。
失败的测试是: 测试:addBin()方法 错误:返回的数字不正确*
这是我的代码:
import java.util.Scanner;
class Main {
public static int [] convertToBinary(int a){
int [] bin = {0,0,0,0,0,0,0,0};
for(int i = bin.length-1; i >= 0; i--){
bin[i] = a%2;
a = a/2;
}
return bin;
}
public static void printBin(int [] b){
int z;
for(z=0; z < b.length; z++){
System.out.print(b[z] + " ");
}
System.out.println();
}
public static int [] addBin(int [] c, int [] d){
int [] added = new int [8];
int remain = 0;
for(int x = added.length -1; x >= 0; x--)
{
added[x] = (c[x] + d[x] + remain) % 2;
remain = (c[x] + d[x] + remain)/2;
}
if (added[0] + c[0] + d[0] == 1){
added[0] = 1;
}
else if( (added[0] + c[0]+ d[0] == 2) || (added[0] + c[0]+ d[0] == 3) )
{
System.out.println("Error: overflow");
}
//System.out.println(added);
//don't need to print added, but it is the only way to check it
return added;
}
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num1 = scan.nextInt();
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num2 = scan.nextInt();
int [] bin;
bin = convertToBinary(num1);
System.out.println("First binary number:");
printBin(bin);
int [] bin1 = bin;
bin = convertToBinary(num2);
System.out.println("Second binary number:");
printBin(bin);
int [] bin2 = bin;
System.out.println("Added:");
{
printBin(addBin(bin1,bin2));
}
}}
如果有人可以看一下我上面的代码,看看他们是否可以告诉我需要更改哪些内容来修复 addbin() 方法,以便它通过所有测试,那就太好了!即使您不确定它是否有效,我们也将不胜感激!谢谢!
最佳答案
您添加的方向错误。
ones digit (2^0) stored at index 0, the twos digit (2^1) stored at index 1, all the way up to the 2^7 digit stored at index 7
这意味着:
int[] num1 = {1,0,1,0,0,0,0,0}; // 5
int[] num2 = {0,1,1,0,1,0,0,0}; // 22
int[] res = addBin(num1, num2); // 27 = {1,1,0,1,1,0,0,0}
您从末尾添加,将结转滚动到左侧:
{ 1,0,1,0,0,0,0,0}
+ { 0,1,1,0,1,0,0,0}
= {1,0,0,0,0,1,0,0,0} // Error: overflow
关于java - 二进制计算器赋值 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34215416/