Question

My code is to print the decimal equivalent of a binary number entered by user.

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter a binary integer: ");
        int b=in.nextInt();
        int digits=1;
        int q=b;
        //determine the number of digits
        while(q/10>=1){     
            ++digits;
            q/=10;
        }
        System.out.println(digits);
        int decimal=0;
        int i=0;
        //pick off the binary number's digits and calculate the decimal equivalent
        while(i<=digits-1){
            decimal+=b/Math.pow(10,i)%10*Math.pow(2,i);
            i++;
        }           
        System.out.println(decimal);

    }

}

When I enter 1101, it outputs 13, which is the right answer. However, when I test the number 11001, the decimal equivalent is supposed to be 25, but it outputs 26. I try to fix it but can't find where the bug is. Can you guys help me out?

Was it helpful?

Solution

The problem is that Math.pow returns a floating-point number, and you're doing floating-point calculations where you think you're doing integer calculations. When i is 4, and you calculate

b/Math.pow(10,i)%10*Math.pow(2,i);

the calculation goes like this:

b = 11001
b / Math.pow(10,i) = b / 10000 = 1.1001 (not 1)
1.1001 % 10 = 1.1001
1.1001 * Math.pow(2,i) = 1.1001 * 16 = 17.6016 (not 16)

This is then cast to an (int) when you add it to decimal. It truncates the last value to 17, but it's too late.

Casting the Math.pow results to an (int) will make it work. But this isn't the right approach anyway. If you want to learn how to do it yourself instead of using parseInt, it's best to input the number as a String (see my earlier comment), and then you don't have to worry about picking off the bits as decimal digits or powers of 10 at all anyway. Even using your approach, instead of Math.pow it would be simpler to keep powerOf10 and powerOf2 integer variables that you modify with powerOf10 *= 10; powerOf2 *= 2; in each loop iteration.

OTHER TIPS

Try using:

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter a binary integer: ");
        int b=in.nextInt();
        int answer = Integer.parseInt(in.nextInt() + "", 2);
        System.out.println("The number is " + answer + ".");
    }
}

2 is for base 2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top