0

The first few digits are always "0"s and the last is "1"... I tried calculated on paper many times according to the steps in the code which I believe its logical and smooth. However it outputs "0"digits in front and "1" at last for every execution and I dun know why...

void dectobin(){
    cout<<"Please input the decimal number to be converted into binary:\n";
    int number;
    cin>> number;

    int nofbits=1;
    while (number>1){
        number=number/2;
        ++nofbits;
    }
    int x= number;
    int bits;

    while (nofbits!=0)
    {
        for (int i=0; i<nofbits-2; i++){
            x=(x/2);
        }
        bits=x%2;
        cout<<bits;
        nofbits--;
        x=number;
        cout<<"x:"<<number<<"\t"<<x<<"\n";
    }
    cout<<"B"<<endl;    
}
int main(){

dectobin();
return 0;
}

Thanks for any help in advance.

Edited by iikitty

1
Contributor
1
Reply
11
Views
2 Years
Discussion Span
Last Post by iikitty
0

i juz carelessly changed the value of "number" after calculating the number of bits needed and causing the error all the time, so now problem solved!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.