私は、このガイドを使用してバイナリ文字列を 10 進数に変換し、2 進数から 10 進数に変換するこのプログラムに取り組んでいます。頭の中で for ループを実行すると、正しい出力が得られます。それでも、プログラムを実行すると、次の奇妙な出力が得られます。
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);
}
}
}