10

私は、このガイドを使用してバイナリ文字列を 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);
        }
    }
}
4

2 に答える 2

3

文字列は 0 ベースなので、0 から < 文字列の長さまで文字列をループする必要がありますがindexOf(...)、これは意味をなさない小さな int の文字列内の場所を検索するため、使用したいものではありません。2 に相当する char が文字列のどこにあるか、または文字列の中にあるかどうかは気にしません。

代わりにcharAt(...)orを使用subString(...)してから int に解析します。私は使うだろう

for (int i = 0; i < binary.length(); i++) {
    int whatNumber = charAt(i) - '0'; // converts a numeric char into it's 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

文字を表す数値は、各シンボルに数値表現を与えた古い ASCII テーブルに基づいています。詳細については、こちらをご覧ください: ASCII テーブル

于 2012-09-17T01:51:03.157 に答える
2

2 つのポイント:

  1. 配列のインデックスは 1 ではなく 0 から始まるため、ループは `for (int i=0; i
  2. と混同indexOf()していsubstring()ます。あなたの場合、binary.indexOf(i)次のことを行います。まず、整数iが文字列に変換されます。次にbinary、 の文字列値に一致する部分文字列を左から右に検索しますi。初めてのループi==11にインデックス 0があるため、これは 0 を返しますbinary。2 回目の値はiです2。には no がない2のでbinary、これは 0 を返します。についてi==3は、 で文字列を探しています3binary、これは決して true ではありません。

メソッドを見てString#substring()ください。これは、あなたが意図したものだと思います。

于 2012-09-17T02:02:32.717 に答える