Click here to Skip to main content
15,888,104 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
C++
 #include<iostream.h>
 #include<conio.h>
 #include<string.h>
void main()
{       clrscr();
	int m,i=0,a,b[100],c,d[100];
	char e='y';
	cout<<"\nProgram to convert decimal number into binary number";
	loop:if(e=='y'||e=='Y')
	{
	cout<<"\nEnter a number:";
	cin>>a;
	do
	{
	b[i]=a%2;
	c=a/2;
	a=c;
	b[i];
	m=i;
	i++;
	}while(a>=2);
	cout<<"\nAnswer:";
	cout<<c;
	for(i=m;i>=0;i--)
	{	cout<<b[i];
	}
	cout<<"\nDo you want to continue:y/Y or n/N:";
	cin>>e;
	goto loop;
	}
	else
	{	cout<<"\nThank you for using the decimal to binary converter in C++";
	}
	getch();
}


When I enter any number preceded with 0. I do not get a correct answer. The output is messed up.
Example:

Input:8

gives correct output.
but
Input:08

gives incorrect and irrelevant output.
Please help me. Thanks.
Posted
Updated 3-Aug-15 8:39am
v2
Comments
Sergey Alexandrovich Kryukov 3-Aug-15 14:05pm    
Did you notice that your code sample starts from
#include
#include
#include
?

I understand that this is the artifact of wrong HTML markup, but who do you think should care about it?
—SA
[no name] 3-Aug-15 14:36pm    
You really, really need to listen to what people are telling you. Add i = 0; inside your loop. Goto? Really? You are taught to use goto?

1 solution

The immediate problem is you didn't reset to zero the value of the variable i. Changing from
C++
{
    cout<<"\nEnter a number:";
to
C++
{
    i = 0;
    cout<<"\nEnter a number:";

shoud fix it.


However, there are troubles at the horizon: your code is simply a mess. Moreover it looks you are using an outdated C++ compiler.

You could write your program this way:
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
  while ( true)
  {
    vector <int> binary;
    int n;
    cout << "please insert a positive number (a negative one  to exit)" << endl;
    cin >> n;
    if ( n < 0) return 0;

    do
    {
      binary.push_back( n % 2);
      n >>= 1;
    } while (n>0);
    for (vector<int>::reverse_iterator rit = binary.rbegin(); rit != binary.rend(); ++rit)
    {
      cout << *rit;
    }
    cout << endl;
  }
}
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 3-Aug-15 15:52pm    
5ed.
—SA
CPallini 4-Aug-15 2:13am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900