Reputation: 53
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
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