我是一名新手程序员,试图编写一个将输入的二进制数转换为十进制数的程序。据我所知,数学和代码是正确的,并且没有返回编译错误,但是输出的数字不是正确的十进制数字。我的代码如下:
String num;
double result = 0;
do {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a binary number or enter 'quit' to quit: ");
num = in.nextLine();
int l = num.length();
if (num.indexOf("0")==-1 || num.indexOf("1")==-1 ){
System.out.println("You did not enter a binary number.");
}
for (int i = 0; i < l; i++)
{
result = result + (num.charAt(i) * Math.pow(2, (l - i)));
}
System.out.println("The resulting decimal number is: " +result);
} while (!num.equals("quit"));
if (num.equals("quit")){
System.out.println("You chose to exit the program.");
return;
}
如果您能提供任何帮助,我们将不胜感激。我尝试尽可能清楚地表达我的问题,但如果您有任何问题,我会尽力回答。我还没做这么久。我所需要的只是有人检查一下,希望能找到我在某个地方犯的错误,谢谢。
最佳答案
改变
result = result + (num.charAt(i) * Math.pow(2, (l - i)));
至
result = result + ((num.charAt(i) - '0') * Math.pow(2, i));
或者更紧凑,
result += (num.charAt(i) - '0') * Math.pow(2, i);
<小时/>
请记住,字符 '0'
与数字 0
不同('1'
和 相同) 1
); num.charAt(i)
返回字符而不是整数。
int a = '0';
int b = 0;
System.out.println(Math.pow(2, a));
System.out.println(Math.pow(2, b));
输出:
2.81474976710656E14
1.0
差别很大不是吗?
关于java - 二进制到十进制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12810237/