C + + decimal conversion to binary instance code _c language

Source: Internet
Author: User

The topic content: Converts decimal integers to binary numbers.

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

Output Description: For each n, enter an n value with a 11-bit width right-aligned, then output "-->", and then output the binary number. The output of each integer n, which occupies one row independently.

Topic Analysis: The specific way to convert a number from decimal to binary is the number is 2, and the result is either 1 or 0, which corresponds to the last digit of the binary, and then the number divided by two, the resulting quotient again to the 2 remainder, the result is the penultimate digit of the corresponding binary. And so on, know that the result divided by 2 is 0.

Reference code:

Copy Code code as follows:

#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-->0\n";
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;
}

Effect as shown:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.