可以通過C++程序?qū)⑷魏问M制數(shù)(基數(shù)為:10(0到9))轉(zhuǎn)換為二進制數(shù)(基數(shù)為:2(0或1))。
十進制數(shù)是一個十進制數(shù),因為它的范圍從0到9,在0到9之間總共有10個數(shù)字。任何數(shù)字組合都是十進制數(shù),例如:223,585,192,0,7等。
二進制數(shù)是2的基數(shù),因為它是0或1。 0和1的任何組合都是二進制數(shù),如:1001,101,11111,101010等。
下面來看看看一些十進制數(shù)和二進制數(shù)。
| 十進制 | 二進制數(shù) |
|---|---|
| 1 | 0 |
| 2 | 10 |
| 3 | 11 |
| 4 | 100 |
| 5 | 101 |
| 6 | 110 |
| 7 | 111 |
| 8 | 1000 |
| 9 | 1001 |
| 10 | 1010 |
步驟1:將數(shù)字除以%(模運算符)2,并將余數(shù)存儲在數(shù)組中
步驟2:通過/(除法運算符)將數(shù)字除以2,
步驟3:重復步驟2,直到數(shù)字大于零
下面來看看看將十進制轉(zhuǎn)換為二進制的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;
}
執(zhí)行上面代碼得到如下結(jié)果 -
Enter the number to convert: 9
Binary of the given number= 1001