C++ decimal to binary instance code

  • 2020-04-02 01:56:09
  • OfStack

Convert decimal integers into binary Numbers.

Input description: the input data contains no more than 50 integers n(-231 < n < 231).

Output description: for each n, right-align the input value of n with the width of 11 bits, and then output "-- > ", and then output binary Numbers. The output of each integer n is a separate row.

The specific method to convert a number from decimal to binary is that the number is mod 2, the result is either 1 or 0, which is the end of the corresponding binary; Then divide that number by two, and the quotient is again mod two, which is the penultimate of the corresponding binary... And so on, we know that dividing by 2 is equal to 0.

Reference code:


#include <iostream> 
#include <fstream> 
#include <string> 
#include <algorithm> 
using namespace std; 

string s; 
int main(int argc,char * argv[]) 
{ 
    int n; 
    while(cin>>n) 
    { 
        if(n==0) 
        { 
                cout<<"          0-->0n"; 
                continue; 
        } 
        s=" "; 
        for(int a=n;a;a=a/2) 
        { 
                s=s+(a%2?'1':'0'); 
        } 
        std::reverse(s.begin(),s.end()); 
        const char *sss=s.c_str(); 
        cout.width(11); 
        cout<<n<<(n<0?"-->-":"-->")<<sss<<"n"; 
    } 
    system("pause"); 
    return 0; 
} 

The effect is as follows:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201310/20131022150901094.png" >


Related articles: