Dug4.0
Dug4.0

Reputation: 53

Convert decimal to hex, can't find my logic error

I am new to C++ and coding in general. I know there is logic error but I can't identify it. I am trying to input a decimal, and concatenate the output as a hexadecimal. It seems to only run the loop once even though the control variable is clearly not yet 0.

int main()
{
    long rem = 0,
    int hex = 0; 
    cout << "enter the number to convert ";
    cin >> rem;     
    hex = rem / 16;
    while (rem > 0)
    {
        rem = rem % 16;
        hex = hex + rem;
        cout << hex << "" << rem << endl;
        rem = rem / 16;
    }
    return 0;
}

Upvotes: 0

Views: 163

Answers (2)

Mr. Handy
Mr. Handy

Reputation: 346

#include <iostream>
using namespace std;
int main() {
    // you have to declare variable independently when you declare different type variable
    long rem = 0;  // you typed (,)
    int hex = 0;

    cout << "enter the number to convert ";
    cin >> rem;

    hex = rem / 16;

    while (rem > 0)
    {
        rem = rem % 16; // after this, rem is lower then 16 (remain operator)
        hex = hex + rem;
        cout << hex << "" << rem << endl;
        rem = rem / 16; // so rem must be 0 because rem is lower then 16
    }

    return 0;
}

Actually your code don't work well even though I fix your question's problem, but this is the reason that your loop run just 1 time.

Upvotes: 0

AndyG
AndyG

Reputation: 41220

If all you need to do is output the value in hex, then you can use the std::hex format flag. E.g:

long rem = 16;
std::cout << std::hex << rem << std::endl; //prints 10

Live Demo

Upvotes: 2

Related Questions