I am to write a program that lets me convert any number into any base.
My program currently outputs "1669" for 366 base 16 when the correct output is 16E. Where is my code screwing up?
#include <iostream>
using namespace std;
int main()
{
int iInter, iBase, iRemainder, i, iMax;
int rgiTable[25];
char cAgain;
do
{
do
{
cout << "Enter an integer greater than zero" << endl;
cin >> iInter;
cout << "Enter a base between the numbers 2 and 16" << endl;
cin >> iBase;
if (iInter < 0)
cout << "Enter a new Integer" << endl;
if (iBase < 2 || iBase > 16)
cout<< "Enter a new base" << endl;
} while (iInter < 0 || (iBase < 2 || iBase > 16));
for (i = 0; iInter > 0; i++)
{
iRemainder = iInter % iBase;
iInter = iInter / iBase;
if (iRemainder == 0)
rgiTable[i] = 0;
if (iRemainder == 1)
rgiTable[i] = 1;
if (iRemainder == 2)
rgiTable[i] = 2;
if (iRemainder == 3)
rgiTable[i] = 3;
if (iRemainder == 4)
rgiTable[i] = 4;
if (iRemainder == 5)
rgiTable[i] = 5;
if (iRemainder == 6)
rgiTable[i] = 6;
if (iRemainder == 7)
rgiTable[i] = 7;
if (iRemainder == 8)
rgiTable[i] = 8;
if (iRemainder == 9)
rgiTable[i] = 9;
if (iRemainder == 10)
rgiTable[i] = 'A';
if (iRemainder == 11)
rgiTable[i] = 'B';
if (iRemainder == 12)
rgiTable[i] = 'C';
if (iRemainder == 13)
rgiTable[i] = 'D';
if (iRemainder == 14)
rgiTable[i] = 'E';
if (iRemainder == 15)
rgiTable[i] = 'F';
iMax = i;
}
while (iMax >= 0)
{
cout << rgiTable[iMax];
iMax--;
}
cout << endl;
cout << "Do you wish to enter more data? y/n" << endl;
cin >> cAgain;
} while (cAgain == 'y'|| cAgain == 'Y');
return 0;
}
When you print a digit using
cout<< rgiTable[iMax];
you are printing an integer. When that integer value is equal to E
, you get the ASCII value of E
, which is 69.
Instead of
int rgiTable [25];
you should use
char rgiTable [25];
In the while
loop, use the characters '0'
- '9'
instead of numbers 0
- 9
.
You can simplify the logic using:
for ( i=0; iInter > 0; i++)
{
iRemainder = iInter % iBase;
iInter = iInter / iBase;
if ( iRemainder < 10 )
{
rgiTable [i] = iRemainder + '0';
}
else
{
rgiTable [i] = iRemainder + 'A' - 10;
}
iMax = i;
}