Java 为什么我的二进制到十进制程序的输出不正确?
我正在开发一个程序,它接受一个二进制字符串并将其转换为十进制,使用将二进制转换为十进制。当我在头脑中运行for循环时,我得到了正确的输出。然而,当我运行我的程序时,我得到了这个奇怪的输出:Java 为什么我的二进制到十进制程序的输出不正确?,java,binary,decimal,Java,Binary,Decimal,我正在开发一个程序,它接受一个二进制字符串并将其转换为十进制,使用将二进制转换为十进制。当我在头脑中运行for循环时,我得到了正确的输出。然而,当我运行我的程序时,我得到了这个奇怪的输出: 1 3 7 15 31 63 127 实际输出应如下所示: 1 2 5 11 22 44 89 我一辈子都搞不懂这件事。为什么我的程序要这样做?以下是当前的源代码: public class BinaryToDecimal { public static void main(String[] args)
1
3
7
15
31
63
127
实际输出应如下所示:
1
2
5
11
22
44
89
我一辈子都搞不懂这件事。为什么我的程序要这样做?以下是当前的源代码:
public class BinaryToDecimal
{
public static void main(String[] args)
{
String binary = "1011001";
int toMultiplyBy;
int decimalValue = 0;
for (int i = 1; i <= binary.length(); i++)
{
int whatNumber = binary.indexOf(i);
if (whatNumber == 0)
{
toMultiplyBy = 0;
}
else
{
toMultiplyBy = 1;
}
decimalValue = ((decimalValue * 2) + toMultiplyBy);
System.out.println(decimalValue);
}
}
}
public类BinaryToDecimal
{
公共静态void main(字符串[]args)
{
字符串binary=“1011001”;
int-to-multiplyby;
整数小数=0;
对于(int i=1;i字符串是基于0的,因此您应该在字符串中循环0到indexOf(…)
,这不是您想要使用的,因为这将搜索小整数字符串中的位置,这是没有意义的。您不关心字符串中与2等价的字符的位置,甚至不关心它是否在字符串中
相反,您希望使用charAt(…)
或子字符串(…)
,然后解析为int
for (int i = 0; i < binary.length(); i++) {
int whatNumber = charAt(i) - '0'; // converts a numeric char into it's int
//...
表示字符的数字基于旧的ASCII表,该表为每个符号提供了一个数字表示。有关详细信息,请查看此处:两点:
indexOf()
与substring()
混淆。在您的示例中,binary.indexOf(i)
执行以下操作。首先,将整数i
转换为字符串。然后从左到右搜索binary
以查找与i
字符串值匹配的子字符串。第一次通过循环i==1
。这将返回零,因为binary
中的索引零处有一个1
第二次,i
的值是2
。binary
中没有2
,因此返回零。对于i==3
,您在binary
中查找字符串3
,这永远不会是真的请看一下
String#substring()
方法,我相信这正是您的初衷。+1欢迎您这么做。祝贺您在这里编写了一个关于问题应该如何处理的示例。1)我认为“indexOf()”可能有一个“off by one”错误,2)我真的不知道您在哪里转换到当前的二次幂,3)是的,“parseInt(str,2)
”更简单、更高效:)这是一个类赋值,所以不幸的是我不允许使用partInt()。如果只是这样,它会让我的生活更轻松…字符串是基于0的,所以你应该从0循环字符串,但indexOf不是你想要使用的。你想使用charAt(…)
或子字符串(…)
然后解析为int。我会自己使用charAt(…)-“0”
。它很有效!太棒了,谢谢你了!我只有一个问题,如果你不介意的话-当我尝试用indexOf(I)
替换charAt(I)
时,它不起作用。然后当我尝试charAt(I)时-“0”
成功了。为什么添加“0”
会突然给它正确的输出?@Kyle:创建一个小程序,看看“0”的int等价物是什么。它不是0,但很久以前确定的一个几乎任意的数字将代表“0”字符。“1”字符比这个字符大1,“2”比“0”大2,所以如果通过减去“0”来规范化int,则会得到字符所代表的数字的int值。
public class CheckChars {
public static void main(String[] args) {
String foo = "0123456789";
for (int i = 0; i < foo.length(); i++) {
char myChar = foo.charAt(i);
int actualIntHeld = (int) myChar;
int numberIWant = actualIntHeld - '0';
System.out.printf("'%s' - '0' is the same as %d - %d = %d%n",
myChar, actualIntHeld, (int)'0', numberIWant);
}
}
}
'0' - '0' is the same as 48 - 48 = 0
'1' - '0' is the same as 49 - 48 = 1
'2' - '0' is the same as 50 - 48 = 2
'3' - '0' is the same as 51 - 48 = 3
'4' - '0' is the same as 52 - 48 = 4
'5' - '0' is the same as 53 - 48 = 5
'6' - '0' is the same as 54 - 48 = 6
'7' - '0' is the same as 55 - 48 = 7
'8' - '0' is the same as 56 - 48 = 8
'9' - '0' is the same as 57 - 48 = 9