Monday, December 12, 2011

Method to convert a binary number to a decimal number?

This method is supposed to convert binary number input by the user to a decimal number. I am having trouble raising the 2 to a power. I get an error message 'possible loss of precision' and it will not compile. The variable 'decval' should contain the final decimal number. Can anyone see what I may be doing wrong? Thanks in advance for your help...





public void bin2dec() {





int length = 0;


int pow = 0;


int decval = 0;





String x = sc.next();


length = x.length();





StringBuffer buffer = new StringBuffer(x);


buffer = buffer.reverse();





while ( length %26gt; -1 ) {


char ch = x.charAt(length);





if (ch == '1') {


decval = decval + Math.pow(2,pow);


}


--length;


++pow;


}





}|||Math.pow returns a double, not an integer





2 + 5.5 makes the Java compiler generate a possible loss of precision error. This is alerting you to the fact that the answer will be 7, not 7.5


This is a feature because these things can be software bugs and cause things like your Martian explorer robot to crash land. Thus you need to tell the compiler you know what you are doing.





so decval = decval + int(Math.pow(2,pow));


would work due to the integer cast.|||Even though you are using integers, Math.pow always returns a double. I would just cast it before adding it to the sum:


decval = decval + (int) Math.pow(2,pow);|||instead of casting the result from Math.pow to an int, just change the decval to a double, as mentioned in your previous question.





That is, change this:


int decval = 0;


to


double decval = 0.0;





Good luck.

No comments:

Post a Comment