C++將十進位轉換為二進位

可以通過C++程式將任何十進位數(基數為:10(0到9))轉換為二進位數(基數為:2(0或1))。

十進位

十進位數是一個十進位數,因為它的範圍從09,在09之間總共有10個數字。任何數字組合都是十進位數,例如:22358519207等。

二進位數

二進位數是2的基數,因為它是0101的任何組合都是二進位數,如:100110111111101010等。

下麵來看看看一些十進位數和二進位數。

十進位 二進位數
1 0
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010

將十進位到二進位轉換演算法

步驟1:將數字除以(模運算符)2,並將餘數存儲在數組中
步驟2:通過/(除法運算符)將數字除以2
步驟3:重複步驟2,直到數字大於零

下麵來看看看將十進位轉換為二進位的C++示例。

#include <iostream>
using namespace std;
int main()
{
    int a[10], n, i;
    cout<<"Enter the number to convert: ";
    cin>>n;
    for(i=0; n>0; i++)
    {
        a[i]=n%2;
        n= n/2;
    }
    cout<<"Binary of the given number= ";
    for(i=i-1 ;i>=0 ;i--)
    {
        cout<<a[i];
    }
    return 0;
}

執行上面代碼得到如下結果 -

Enter the number to convert: 9
Binary of the given number= 1001

上一篇: C++矩陣乘法 下一篇: C++將數字轉換字元