0

私が取り組んでいるこのプログラムは、問題があることを除けば、すべて問題ないようです。これがコードです

#include <iostream>
#include <fstream>

using namespace std;

/*
Function Name: CalculateBinary
CalculateBinary takes a number from the main function and finds its binary form.
*/

void CalculateBinary( long InputNum)
{   
    //Takes InputNum and divides it down to "1" or "0" so that it can be put in binary form.
    if ( InputNum != 1 && InputNum != 0)
        CalculateBinary(InputNum/2);

    // If the number has no remainder it outputs a "0". Otherwise it outputs a "1". 
    if (InputNum % 2 == 0)
        cout << "0";
    else
        cout << "1";
}


void main()
{
    // Where the current number will be stored
      long InputNum;

    //Opens the text file and inputs first number into InputNum. 
    ifstream fin("binin.txt");
    fin >> InputNum;

    // While Input number is not 0 the loop will continue to evaluate, getting a new number each time.
    while (InputNum >= 0)
    {
        if(InputNum > 1000000000)
            cout << "Number too large for this program ....";
        else
            CalculateBinary(InputNum);

        cout << endl;
        fin >> InputNum;        
    }
}

これが私が読んでいるテキストファイルです

12
8764
 2147483648
2
-1

私が8764に到達すると、この番号を何度も何度も読み続けます。2147483648は無視されます。InputNumをlonglongとして宣言することで、これを解決できることはわかっています。しかし、なぜそれがこれをしているのか知りたいですか?

4

4 に答える 4

4

That is the usual problem with such loops which you've written.

The correct and the idiomatic loop is this:

ifstream fin("binin.txt");
long InputNum;
while (fin >> InputNum && InputNum >= 0)
{
   //now construct the logic accordingly!
    if(InputNum > 1000000000)
         cout << "Number too large for this program ....";
    else
         CalculateBinary(InputNum);
    cout << endl;
}
于 2011-09-13T17:03:30.083 に答える
2

longその数は、保存するには大きすぎるため、fin >> InputNum;何もしません。while(fin >> InputNum) { ... }失敗するとすぐにループを終了するか、少なくともストリームの状態を確認するため、常にとして読み取る必要があります。

于 2011-09-13T17:02:11.510 に答える
0

longプラットフォームのタイプは32ビット幅であるように見えます。数値2147483648(0x80000000)は、符号付き32ビット整数として表すには大きすぎます。符号なし型(明らかに負の数では機能しません)または64ビット整数のいずれかが必要です。

また、読み取りが成功したかどうかを確認する必要があります。

  ...
  cout << endl;
  if (!(fin >> InputNum)) break; // break or otherwise handle the error condition
}
于 2011-09-13T17:00:45.600 に答える
0

EOFをチェックしないため、ループに永久に閉じ込められます。成功した場合はfin >> InputNum式が返され、そうでない場合はコードを次のように変更すると問題が解決します。truefalse

while ((fin >> InputNum) && InputNum >= 0)
{
  // ...
}
于 2011-09-13T17:01:46.480 に答える