#include<iostream>
#include<conio.h>
using namespace std;
void main()
{
int num1,num2,ans,rem;
cout<<"enter the number in decimal:"<<endl;
cin>>num1;
cout<<"number in binary is:"<<endl;
while(num1!=1)
{
rem=num1%2;
num1=num1/2;
cout<<rem;
}
getch();
}
Yes, it is when the program contains errors and bad practices.
This site is frequented by posters just learning C++. To see a program that contains errors and bad practices is misleading to C++ learners.
Problems with your code:
Line 2: conio.h header is deprecated and should not be used.
Line 3: Use of usingnamespace std; should be avoided.
Line 4: void main () is not valid. main MUST return an int.
Line 6: num2 and ans are not used. Why are they here?
Line 6: variables are poorly named.
Line 10-15: program loops forever if 0 is entered. program doesn't output anything if 1 is entered. Program gives incorrect answer for other values.
Line 15: getch is deprecated
PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/
#include <iostream>
#include <string>
int main ( )
{
int number, numCopy;
bool isNegative = false;
std::string binaryNumber = "";
do {
std::cin.sync ( ); std::cin.clear ( ); // clear the error and the input stream
std::cout << "Please enter an integer: "; // ask for a number
std::cin >> number; // get a number
if ( !std::cin ) std::cout << "\nThat number could not be read. Please try again.\n\n";
} while ( !std::cin );
if ( number < 0 )
{
isNegative = true;
number -= number * 2; // make number positive
}
if ( number ) // if number is not 0
{
numCopy = number; // make a copy of the original number
while ( numCopy ) // and get its value in binary
{
if ( numCopy & 1 ) binaryNumber = '1' + binaryNumber;
else binaryNumber = '0' + binaryNumber;
numCopy = numCopy >> 1;
}
}
else binaryNumber = "0";
if ( isNegative ) // if the number is negative, take the two's complement
{
size_t strLength = binaryNumber.length ( );
for ( size_t i = 0; i < strLength; ++i ) // get inverse
{
if ( binaryNumber[i] == '0' ) binaryNumber[i] = '1';
else binaryNumber[i] = '0';
}
for ( size_t i = strLength - 1; i >= 0; --i ) // and add one
{
if ( binaryNumber[i] == '0' )
{
binaryNumber[i] = '1';
break;
}
else binaryNumber[i] = '0';
}
if ( binaryNumber[0] == '0' ) binaryNumber.erase ( 0, 1 ); // if the first char is 0, erase it
}
std::cout << '\n' << number << " is represented in binary as " << binaryNumber << "\n\n";
}