Hi all!
I'm a beginner to C++ and wanted to try my skill at creating a decimal to binary converter in the console. I tried two different methods, but I failed at both.
My first program was an attempt at being organized and using multiple functions and snaking the output through each of them to reach the binary value. The premise was simple(or so I thought): Get decimal, check for the highest degree of 2 allowed in the value, record the value as a '1' in an array. Then it should subtract the value of 2^(that power) and recheck the values, continuing until there's nothing left. The problem is that I seem to get the same answer (completely incorrect) every time I put a value. Here's the code.
#include <iostream>
#include <math.h>
using namespace std;
int aExp[30] = { 0 };
int Check(int nCount2)
{
int nExp = 0;
bool bContinue = true;
cout << endl <<"in check";
do
{
if(nCount2 > (pow(2,nExp)))
{
nExp++;
bContinue = true;
cout << endl << "At " << nExp << endl;
}
else (bContinue = false);
}
while (bContinue);
aExp[nExp] = 1;
};
int Tally(int nCount)
{
static int nTally = 0;
for(int iii = 0; iii < 30; iii++)
{
if (aExp[iii] == 1) {nTally = (nTally + pow(2,iii));};
};
return nTally;
};
void Count(int nStart)
{
static int nCount = nStart;
cout << endl << "in Count";
while (nCount > 0)
{
cout << endl << "before Check";
Check(nCount);
nCount = Tally(nStart);
};
};
int main()
{
cout << "Decimal to Binary" << endl;
cout << endl << "Enter the starting decimal number: ";
int nStart = 0;
cin >> nStart;
Count(nStart);
for (int iii = 29; iii >= 0; iii--) cout << aExp[iii];
cin.clear();
cin.ignore(255, 'n');
cin.get();
return 0;
}
Now, the second attempt after 2.5 frustrating hours. I tried to make this straightforward with an approach someone else took. Go through a for() loop starting at degree 30 and work the way down systematically. It seems to always just output '1' as the answer.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
cout << "Decimal to Binary" << endl << "Enter decimal value: ";
int nDecimal = 0;
cin >> nDecimal;
static int nCount = nDecimal;
for (int iii = 30; iii >= 0; iii--)
{
if (nCount > (pow(2,iii)))
cout << "0";
else
{cout << "1"; nCount = (nCount - (pow(2,iii)));};
};
cout << "after";
cin.clear();
cin.ignore(255, 'n');
cin.get();
return 0;
}
Any help with this would be appreciated. Maybe it's all the built-up frustration clouding something, but I can't figure it out. Thank you!