0

ユーザーが2進数で非常に大きな数値を入力した場合、出力には0が表示されます。この関数を変更して、より大きな数値で機能するようにするにはどうすればよいですか?

{ 
    // Binary to Decimal converter function

    int bin_Dec(int myInteger)
    {
    int output = 0;
    for(int index=0; myInteger > 0; index++ )
    {
    if(myInteger %10 == 1)
        {
            output += pow(2, index); 
        }
    myInteger /= 10;
    }
    return output;
    }

    int _tmain(int argc, _TCHAR* argv[])
    { // start main

    int myNumber;

    // get number from user

    cout << "Enter a binary number, Base2: "; // ask for number 
    cin >> myNumber;

    //print conversion

    cout << "Base10: " << bin_Dec(myNumber) << endl; // print conversion
    system("pause");

    } // end of main
}
4

1 に答える 1

1

「バイナリ番号」を。として使用するのはやめましょうint。intのサイズには制限があります。最大値は通常約20億、つまり10桁です。数字をビットとして悪用している場合、最大10ビットになります。これは1023に相当します。

string代わりに取ってください。あなたは入力で有用な計算をしていません。とにかくそれを数字の文字列として使用しているだけです。

// oh, and unless you have good reason...this would be better unsigned.
// Otherwise your computer might catch fire when you specify a number larger
// than INT_MAX.  With an unsigned int, it's guaranteed to just lop off the
// high bits.
// (I may be overstating the "catch fire" part.  But the behavior is undefined.)
unsigned int bin_to_dec(std::string const &n) {
    unsigned int result = 0;
    for (auto it = n.begin(); it != n.end(); ++it) {
        result <<= 1;
        if (*it == '1') result |= 1;
    }
    return result;
}

ただし、C ++ 11を使用している場合は、ベース2を指定するときにこれを行うstd::stoiファミリ(で定義<string>)があります。学習目的で車輪の再発明を行う場合を除いて、それらを使用することをお勧めします。

std::cout << "Base10: " << std::stoi(myNumberString, 0, 2) << '\n';
于 2013-03-09T17:47:16.053 に答える