gpt4 book ai didi

java - 二进制到十进制转换 Java 代码错误

转载 作者:行者123 更新时间:2023-12-01 14:50:56 25 4
gpt4 key购买 nike

所以我正在做一个项目,我必须进行从二进制数到十进制等的转换。这是我到目前为止的代码,有一个错误。在诸如 1101 之类的二进制数中,假设输出的十进制数是 13,但代码中输出的数字是 11。此错误发生在所有以一堆 1 开头且类似于单个 0 的二进制数中。

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
*
*/
}

}

最佳答案

按照从右向左读取二进制字符串的方式计算您的预期结果;但是,您的代码从左到右读取二进制字符串。

更改此:

for (double index = 0; index < charArray.length; index++){

对此:

for (double index = charArray.length - 1; index >= 0; index--) {

您还应该更改为使用整数作为索引,如下所示:

for (int index = charArray.length - 1; index >= 0; index--) {

关于java - 二进制到十进制转换 Java 代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14865207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com