0

我是一年级计算机科学专业的学生。这个问题已经被问过很多次了,我已经经历了这些。但我仍然无法在当前代码中找到需要修复的地方。我已经编写了将十进制转换为二进制的代码。以下是示例输入和输出。

样本输入

4
101
1111
00110
111111

样本输出

5
15
6
63

我理解概念和二进制转换。但是,我无法输入指定数字的二进制值并且得到不正确的输出。我不能使用 Integer.parseInt。下面是从二进制到十进制的粗略转换练习。

Binary to Decimal 
    1       0       1       0 -binary
    3       2       1       0 -power
    2       2       2       2 -base
    1*2^3 + 0*2^2 + 1*2^1 + 0*2^0
    8     + 0     + 2     + 0     = 10

代码

public class No2_VonNeumanLovesBinary {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int numTotal, binaryNum, decimalNum = 0, remainder;
        numTotal = s.nextInt();
        for(int i = 0 ; i <= numTotal; i++){
        // This is to get binaryNum input. However I am not getting the expected result.
            binaryNum = s.nextInt();
            while(binaryNum != 0){
                remainder = binaryNum % 10;
                decimalNum = decimalNum + (remainder * i);
                i = i * 2;
                binaryNum = binaryNum / 10;
            }
            System.out.println(decimalNum);
        }
    }
}

谢谢!

4

1 回答 1

1

有两件事要解决。在 while 循环中使用 i 以外的变量。打印值后将 decimalNum 重置为 0。IE,

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    int numTotal, binaryNum, decimalNum = 0, remainder;
    numTotal = s.nextInt();
    for(int i = 0 ; i <= numTotal; i++){
        // This is to get binaryNum input. However I am not getting the expected result.
        binaryNum = s.nextInt();
        int j = 1;
        while(binaryNum != 0){
            remainder = binaryNum % 10;
            decimalNum = decimalNum + (remainder * j);
            j = j * 2;
            binaryNum = binaryNum / 10;
        }
        System.out.println(decimalNum);
        decimalNum = 0;
    }       
}
于 2020-06-12T05:03:39.103 回答