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.

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.