十进制转二进制,格式化输出

描述
将十进制整数转换成二进制数

输入
输入数据中含有不多于50个整数n(-2^16<n<2^16)。

输出
对于每个n,以11位的宽度右对齐输出n值,然后输出 –> ,再然后输出二进制数。每个整数n的输出,独立占一行。

样例输入1
2
0
-12
1

样例输出1
2―->10
0–>0
-12–>-1100
1–>1

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int num = 0;
    while (cin >> num)
    {
        string sBinary;
        int temp = abs(num);
        if (temp == 0)
        {
            cout << " 0-->0\n";
            continue;
        }
        while (temp)
        {
            if (temp & 0x01)
                sBinary += '1';
            else
                sBinary += '0';
            temp >>= 1;
        }
        reverse(sBinary.begin(), sBinary.end());
        cout.width(11);
        cout << num << (num > 0 ? "-->" : "-->-") << sBinary << endl;
    }
    return 0;
}

巧妙使用string类的加法以及cout类的setw函数和对string逆序排列。

    原文作者:进制转换
    原文地址: https://blog.csdn.net/u011544909/article/details/78974324
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞