所以我正在做一個項目,我必須做從二進制數轉換爲小數等。 這是我的代碼到目前爲止,還有一個錯誤。在一個二進制數字如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(...)'任何這一點。在論文中寫出你如何解決這個問題以找到你的算法,但同樣的,將高功率和不必要的浮點方法調用放在只需要簡單代數的東西上。請注意,您過度使用評論是相當分心的。 – 2013-02-13 23:30:21
它已經在這裏回答:http://stackoverflow.com/questions/7437987/how-to-convert-binary-string-value-to-decimal – fons 2013-02-13 23:31:48