繁体   English   中英

十进制输入然后二进制输入(不使用 Integer.parseInt)

[英]Decimal input then Binary input (without using Integer.parseInt)

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

样本输入

4
101
1111
00110
111111

样品 Output

5
15
6
63

我理解概念和二进制转换。 但是,我无法输入指定数字的二进制值,并且 output 不正确。 我不能使用 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);
        }
    }
}

谢谢!

有两件事要解决。 在 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;
    }       
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM