0

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;
}
jww
  • 97,681
  • 90
  • 411
  • 885
Dug4.0
  • 53
  • 2
  • if you just want to print number in hexa decimal try: http://stackoverflow.com/questions/3649026/how-to-display-hexadecimal-numbers-in-c – Anil8753 Apr 10 '15 at 03:43
  • `cout << hex` should be `cout << std::hex`. Your actual code outputs your local variable `hex`. – M.M Apr 10 '15 at 03:50

2 Answers2

2

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

AndyG
  • 39,700
  • 8
  • 109
  • 143
0
#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.

Mr. Handy
  • 356
  • 2
  • 14