Kyl*_*ans 10 java binary decimal
我正在研究这个带有二进制字符串并将其转换为十进制的程序,使用本指南将二进制转换为十进制.当我在头脑中经历for循环时,我得到了正确的输出.然而,当我运行我的程序时,我得到了这个奇怪的输出:
1
3
7
15
31
63
127
Run Code Online (Sandbox Code Playgroud)
实际输出应如下所示:
1
2
5
11
22
44
89
Run Code Online (Sandbox Code Playgroud)
我无法想象我的生活.为什么我的程序会这样做?这是当前的源代码:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
字符串是基于 0 的,因此您应该从 0 到 < 字符串长度循环遍历字符串,但是indexOf(...), 不是您想要使用的,因为这将搜索字符串中小整数的位置,这是没有意义的。您不关心相当于 2 的 char 位于字符串中的哪个位置,甚至不关心它是否位于字符串中。
相反,您想使用charAt(...)orsubString(...)然后解析为 int。我会用
for (int i = 0; i < binary.length(); i++) {
int whatNumber = charAt(i) - '0'; // converts a numeric char into it's int
//...
Run Code Online (Sandbox Code Playgroud)
要查看它在做什么,请创建并运行:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
返回:
'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
Run Code Online (Sandbox Code Playgroud)
表示字符的数字基于旧的 ASCII 表,该表为每个符号提供了数字表示形式。有关这方面的更多信息,请查看此处:ASCII 表