Issue with Infite Loop
I have a problem. This code is not giving the results it should. It should out number to large to the console and for some reason it is ignoring the if the statement when doing this. Also, in this program InputNum
should remain of the long data type.
#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()
{
//开发者_StackOverflow Where the current number will be stored
long InputNum = 3000000000;
//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;
}
}
CalculateBinary(InputNum)
does NOT modify the value of InputNum
, so its value would be always the same (300000000) and the while loop never end.
The if
statement is not being ignored; you just aren't modifying InputNum
. Its always going to keep its initial value. You are passing InputNum
by value, not by reference. Therefore, CalculateBinary()
is using a copy of InputNum
.
Yes, it will be infinite. That's because you have a:
while (InputNum >= 0)
line in main
but you never change the value of InputNum!
Remove the while
loop altogether. It looks like you may need it when you start reading your numbers in from binin.txt
but certainly not yet.
Looks like you are expecting the last number in the file to be less than 0 to terminate your program. Instead it's better to detect the end of the file. Try uncommenting your file code and using the while condition instead:
while (fin.good())
精彩评论