可以通過(guò)C++程序?qū)⑷魏问M(jìn)制數(shù)(基數(shù)為:10(0到9))轉(zhuǎn)換為二進(jìn)制數(shù)(基數(shù)為:2(0或1))。
十進(jìn)制數(shù)是一個(gè)十進(jìn)制數(shù),因?yàn)樗姆秶鷱?code>0到9,在0到9之間總共有10個(gè)數(shù)字。任何數(shù)字組合都是十進(jìn)制數(shù),例如:223,585,192,0,7等。
二進(jìn)制數(shù)是2的基數(shù),因?yàn)樗?code>0或1。 0和1的任何組合都是二進(jìn)制數(shù),如:1001,101,11111,101010等。
下面來(lái)看看看一些十進(jìn)制數(shù)和二進(jìn)制數(shù)。
| 十進(jìn)制 | 二進(jìn)制數(shù) |
|---|---|
| 1 | 0 |
| 2 | 10 |
| 3 | 11 |
| 4 | 100 |
| 5 | 101 |
| 6 | 110 |
| 7 | 111 |
| 8 | 1000 |
| 9 | 1001 |
| 10 | 1010 |
步驟1:將數(shù)字除以%(模運(yùn)算符)2,并將余數(shù)存儲(chǔ)在數(shù)組中
步驟2:通過(guò)/(除法運(yùn)算符)將數(shù)字除以2,
步驟3:重復(fù)步驟2,直到數(shù)字大于零
下面來(lái)看看看將十進(jìn)制轉(zhuǎn)換為二進(jì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