Так что я делаю проект, где мне нужно делать преобразования из двоичных чисел в десятичные числа и т. Д. Это мой код до сих пор, и есть ошибка. В двоичном числе, таком как 1101, десятичное число, которое должно выйти, равно 13, но число, которое выходит из кода, равно 11. Эта ошибка происходит со всеми двоичными числами, начинающимися с пучка 1 и как один 0.Ошибка двоичного преобразования кода Java
import java.util.*; // imports everything in java.util
public class newCalculator{
* Conversion asks the user for a binary number. It converts the input to a decimal number
* using arrays and then displays the answer to the screen.
*/
public static void main (String[]args){ // creates the main method
binaryToDecimal(); //calls the user defined method binaryToDecimal
}
public static void binaryToDecimal() {
Scanner scan = new Scanner(System.in); // Creates a new Scanner
System.out.println("Input a Binary Number"); // Asks the user to input their number
String binary = scan.next(); // Creates a new String that stores the value of the input
char[] charArray = binary.toCharArray(); //Create a new Array and implements in the input
double answer = 0; // Creates a new double called answer setting it to zero
for (double index = 0; index < charArray.length; index++){//For loop
if (charArray[(int)index] == '1') {//If statement that allows the binary input to work
answer = answer + Math.pow(2.0, index);//Sets the answer with the math class power of 2
}
}
System.out.println(answer);//Prints out the final conversion result
/* Test Cases Expected Result Output
* 101 5 5
* 11 3 3
* 1 1 1
* 1101 13 11<--
* 111 7 7
* 1000001 65 65
* 1111 15 15
* 1001 9 9
* 11101 29 23<--
* 10101 21 21
*
*/
}
}
не используйте 'Math.pow (...)' для любого из этого. Выпишите на бумаге, как бы вы решили это, чтобы найти свой алгоритм, но опять же, оставите мощные и ненужные вызовы метода с плавающей запятой из того, что требует только простой алгебры. Обратите внимание, что чрезмерное использование комментариев довольно отвлекает. –
Это уже ответили (а): http://stackoverflow.com/questions/7437987/how-to-convert-binary-string-value-to-decimal – fons