2016-02-13 5 views
3

For this lab, you will enter two numbers in base ten and translate them to binary. You will then add the numbers in binary and print out the result. All numbers entered will be between 0 and 255, inclusive, and binary output is limited to 8 bits. This means that the sum of the two added numbers will also be limited to 8 bits. If the sum of the two numbers is more than 8 bits, please print the first 8 digits of the sum and the message "Error: overflow". Your program should represent binary numbers using integer arrays, with the 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. Your program should include the following methods:Binary Calculator Назначение

  • int[] convertToBinary(int b) Translates the parameter to a binary value and returns it stored as an array of ints.
  • void printBin(int b[]) Outputs the binary number stored in the array on one line. Please note, there should be exactly one space between each output 0 or 1.
  • int[] addBin(int a[], int b[]) Adds the two binary numbers stored in the arrays, and returns the sum in a new array of ints.

При вводе кода в CodeRunner (который проверяет код и возвращает оценку в зависимости от результатов каждого теста), я не могу пройти один из тестов. Это сообщение, которое я получаю:

* У вас было 43 из 44 тестов. Ваша оценка - 97%.

Испытания, которые не смогли были: Тест: метод addBin() Неправильно: Неправильный номер возвращается *

Heres мой код:

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"); 
     } 
     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

ElseIf, который печатает '«Ошибка: переполнение»', не подстраивается добавило "вернуться«первые 8 цифры. не знаю, как выглядит анальная java, но большинство языков позволяют динамически расширять массивы. Кроме того, массив base 0 заканчивается на 8, если при ограничении цифр на массивах с нулевым значением должно быть 7. –

+0

Я изменил его на 7, и мой счет снизился до 50%. Я весь день борюсь с этим, есть ли что-то еще, что вы видите не так. – NotaMan

+0

Я немного смущен, что вы подразумеваете под этим, не могли бы вы уточнить? – NotaMan

ответ

2

Привет, прежде всего, прошу прощения за мой английский, но я думаю, что ваше задание принимает 1 и 255 тоже. Поэтому я добавил два из них и получил 1 0 0 0 0 0 0 0 в вашем коде. Но я думаю, что это должно быть 0 0 0 0 0 0 0 0 с ошибкой переполнения. Поэтому я немного изменил код.

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 (remain!=0) { 

     System.out.println("Error: overflow"); 
    } 
    return added; 
} 

Это мой первый ответ на сайте, так что я надеюсь, что он работает для теста

+0

К сожалению, это не так, ошибка – NotaMan

+0

@NotaMan Я снова прочитал текст назначения. Он говорит «цифра (2^0), хранящаяся в индексе 0, двузначная цифра (2^1), хранящаяся по индексу 1, вплоть до цифры 2^7, хранящейся в индексе 7.». В вашем коде я думаю, что все наоборот. –