这是分配要求的描述:
在本实验中,您将以10为基数输入两个数字,并将其转换为二进制。然后,您将以二进制形式添加数字并打印出结果。输入的所有数字将在0到255之间(含0和255),并且二进制输出限制为8位。这意味着两个相加数的总和也将被限制为8位。如果两个数字的总和超过8位,请打印总和的前8位数字和消息“错误:溢出”。您的程序应使用整数数组来表示二进制数,其中一位(2 ^ 0)存储在索引0,两位(2 ^ 1)存储在索引1,一直到2 ^ 7数字存储在索引7.您的程序应包括以下方法:int [] convertToBinary(int b)将参数转换为二进制值,并以int数组形式存储返回该值。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()方法,以便它可以通过所有测试,那就太好了!即使您不确定它是否会起作用,也将不胜感激任何帮助!谢谢!
您添加的方向错误。
1位数字(2 ^ 0)存储在索引0,2位数字(2 ^ 1)存储在索引1,一直到2 ^ 7位存储在索引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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句