Transform a decimal number into a binary number

The outputs:

Input a decimal number range from 1 to 31: 16
1 0 0 0 0


Input a decimal number range from 1 to 31: 19
1 0 0 1 1

The codes:

#include <iostream>
using namespace std;
int main()
{
    cout << "Input a decimal number range from 1 to 31: ";
    int n;
    cin  >> n;
    int a[5];
    int i =0,j = 0;
    while (n > 0){
        a[j++] = n%2;
        n = n/2;
    }
    for(int i = j; i < 5; ++i){
        a[i] = 0;
    }
    for(int i =4; i >=0; --i){
        cout << a[i] << " ";
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_38396940/article/details/120664465