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!

Nick Evan commented: Good first post! +16

Recommended Answers

All 8 Replies

Hello
if i have got u right, the problem is quite simple and you are complicating it unnecessarily.
i have got code ready, but i am not posting it now.
use these steps
1.read decimal
2.store decimal modulo 2 in a array called binary
3.divide decimal by 2
4.repeat 2 & 3 as long as decimal != 0
5.print array binary backwards
Vinayak

Ninja-edit: I realized my error in the program below, and have fixed it. The program works really well. Thank you for the help. However, if it isn't too much to ask, would it be possible to show the error of my ways in my first two programs so that I can attempt to learn from those mistakes? If not, that's ok. Maybe it really just was overtly complicated for the task. Thanks again!

Hi! Thanks for the response. I know that I was making it unnecessarily complicated, but my goal was for "it works" rather than "it's optimal." Though, it obviously caused me problems. In any case, I followed your steps for the conversion and made a program for it. However, it doesn't seem to understand to assign anything but zeros to the array, leaving me with a 16bit array of zeros.

#include <iostream>

using namespace std;

int main()
{
    int nDecimal = 0;
    cout << "Decilmal to Binary\nEnter the decimal value: ";
    cin >> nDecimal;
    int anValues[16] = { 0 };
    int n = 0;
    do
    {
        anValues[n] = nDecimal % 2;
        nDecimal/2;
        n++;
    }
    while (nDecimal != 0);
    for (int iii = 16; iii >= 0; iii--) cout << anValues[iii];
    cin.clear();
    cin.ignore(255, 'n');
    cin.get();
    return 0;
}

Perhaps it's the fact that assigning array index values with variables is not permissible? Other than that potential problem, I don't understand what can be going wrong. If that IS the issue, how do you suggest I got about fixing that? Thank you.

That isn't the issue. I've added some debugging code in your loop so you can see what's going on. The displays may surprise you!

#include <iostream>

using namespace std;

int main()
{
    int nDecimal = 0;
    cout << "Decilmal to Binary\nEnter the decimal value: ";
    cin >> nDecimal;
    int anValues[16] = { 0 };
    int n = 0;
    do
    {
	cout << "\n\nTop of do-while: n=" << n << " nDecimal=" << nDecimal << " : ";
	for (int iii = 16; iii >= 0; iii--) cout << anValues[iii];	
	cout << "\n\n";		
        cin.get();

	anValues[n] = nDecimal % 2;
        nDecimal/2;
        n++;
		
	cout << "\n\nBottom of do-while: n=" << n << " nDecimal=" << nDecimal << " : ";
        for (int iii = 16; iii >= 0; iii--) cout << anValues[iii];		
        cout << "\n\n";		
        cin.get();
    }
    while (nDecimal != 0);
    for (int iii = 16; iii >= 0; iii--) cout << anValues[iii];
    cin.clear();
    cin.ignore(255, 'n');
    cin.get();
    return 0;
}

As to you first two attempts, I'm not guaranteeing this is the problem, but the pow function doesn't take 2 integers. I suggest writing you own pow function that takes 2 integers and using it instead of math.h's pow function. I am wondering whether there is some roundoff error. See if you get different results.

>> I realized my error in the program below, and have fixed it. The program works really well.


So the code posted has been changed? You can edit the code as well when you edit a post. Anyway, I saw three errors. I don't know which you have fixed, so I'll point them out:

Line 16 --> / Needs to be changed to /=
Line 22 --> 'n' should be '\n'
Line 20 --> 16 needs to be changed to 15.


And what if they enter a number that's greater than 2^16 - 1?

>> I realized my error in the program below, and have fixed it. The program works really well.


So the code posted has been changed? You can edit the code as well when you edit a post. Anyway, I saw three errors. I don't know which you have fixed, so I'll point them out:

Line 16 --> / Needs to be changed to /=
Line 22 --> 'n' should be '\n'
Line 20 --> 16 needs to be changed to 15.


And what if they enter a number that's greater than 2^16 - 1?

Thank you for the suggestions. I realized the problem of just dividing it and assigning it to the divided value. That was changed. I didn't know about the n vs the escaped \n, I just saw someone use those three lines to keep the program open and have been using it. And drats, the n-1 thing will take a while for me to get used to.

I will include my own exponent function in that code and report the results back. I've been following an online tutorial at www.learncpp.com and it doesn't talk much about including different libraries as of yet, so I just googled a power function, assuming both as integer parameters.

What a stupid little mistake to get hung-up on. Hopefully I'll learn to avoid those quickly. Thank you for the support. The debugging code made it really easy to notice my error. I tried adding some, but I can tell the difference between your informative code and my code. I will continue working on it just to learn from my mistakes.

You are EXTREMELY close on your second original attempt. In addition to writing the correct pow function, focus on line 15. Forget the loop. Just focus on the FIRST iteration. Pick a number, any number, and do the comparison on line 15 and see if the first trip through the loop correctly displays the '0' or '1' for the most significant bit.

if (nCount > (pow(2,iii)))

Fix that line and the pow function and see if everything works. You'll feel a little discouraged that you spent 2 1/2 hours for this one silly bug, but you'll also feel a little better because you nailed most of it.

As far as 'n' versus '\n', presumably you are trying to pause till the person hits the Enter key, which is represented by '\n', not 'n'. Without the \, the magic character will be the actual letter n, so until the person actually hits the 'n' key on the keyboard, you can't move on.

I appreciate all the help that I got in this thread. Sorry for the late response. Everything got put on hold for school, but it's spring break now! Anyways, marked this solved, and once again, I appreciate it!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.