'How to debug my decimal to binary conversion program?
I have created a code to for decimal to binary conversion, but I'm having issues in the output.
Have a look at the output then the code.
Output:
Decimal to Binary Conversion
Enter Number
58
rem = 0
rem = 1
rem = 0
rem = 1
rem = 1
rem = 1
Binary = 1111 // here it should print 111010 (the obtained remainders in reverse order)
Code:
#include <iostream>
using namespace std;
void decimalToBinary(){
int n,i,rem;
cout<<"Decimal to Binary Conversion"<<endl;
cout<<"Enter Number"<<endl;
cin>>n;
for(i=0;i<100;i++)
{
rem=n%2;
n=n/2;
cout<<"rem = "<<rem<<endl;
if (n == 1){
break;
}
else if (n == 0){
break;
}
}
cout <<"rem = " << n << endl;
cout << "Binary = " << n << rem << rem << rem << endl;
}
int main()
{
decimalToBinary();
return 0;
}
How can I attain the required output? I should be able to achieve the output in reverse order.
Solution 1:[1]
Look at the below line properly:
cout << "Binary = " << n << rem << rem << rem << endl;
See? You are basically printing out n 1 time and rem 3 times, which will definitely not give you the desired output.
The following works:
// ...
#include <algorithm>
void decimalToBinary() {
int n, rem;
std::string binary; // This will store our binary number
cout << "Decimal to Binary Conversion" << endl;
cout << "Enter Number" << endl;
cin >> n;
for (int i = 0; i < 100; i++)
{
rem = n % 2;
n = n / 2;
cout << "rem = " << rem << endl;
binary.push_back(std::to_string(rem)[0]);
if (n == 1) {
break;
}
else if (n == 0) {
break;
}
}
cout << "rem = " << n << endl;
reverse(binary.begin(), binary.end()); // Reverse the string `binary`
cout << "Binary = " << n << binary << endl;
}
// ...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Solved Games |
