鍍金池/ 教程/ C++/ C++將十進(jìn)制轉(zhuǎn)換為二進(jìn)制
C++用戶定義異常
C++ this指針
C++存儲類
C++函數(shù)
C++交換變量值
C++ continue語句
C++注釋
C++函數(shù)遞歸
C++ goto語句
C++函數(shù)-通過值調(diào)用和引用調(diào)用
C++重載
C++語言歷史
C++反轉(zhuǎn)數(shù)字
C++ try/catch語句
C++是什么?
C++變量
C++ break語句
C++運算符
C++第一個程序
C++繼承
C++虛函數(shù)
C++將十進(jìn)制轉(zhuǎn)換為二進(jìn)制
C++矩陣乘法
C++對象和類
C++基礎(chǔ)輸入輸出(cin,cout,endl)
C++文件和流
C++求素數(shù)
C++ if/else語句
C++友元函數(shù)
C++命名空間
C++面向?qū)ο蟾拍?/span>
C++階乘
C++關(guān)鍵字
C++重載
C++聚合
C++結(jié)構(gòu)體
C++的特點(特性)
C++打印字母表三角
C++ switch語句
C++多態(tài)
C++ do-while循環(huán)
C++字符串
C++ static關(guān)鍵字
C++錯誤處理
C++ for循環(huán)
C語言與C++的區(qū)別
C++ while循環(huán)
C++開發(fā)環(huán)境的安裝
linux環(huán)境下編譯C++ 程序
C++枚舉
C++指針
C++斐波納契數(shù)列
C++阿姆斯壯數(shù)字
C++接口
C++教程
C++數(shù)組
C++數(shù)據(jù)抽象
C++回文程序?qū)嵗?/span>
C++打印數(shù)字三角
C++將數(shù)組傳遞到函數(shù)
C++多維數(shù)組
C++將數(shù)字轉(zhuǎn)換字符

C++將十進(jìn)制轉(zhuǎn)換為二進(jìn)制

可以通過C++程序?qū)⑷魏问M(jìn)制數(shù)(基數(shù)為:10(0到9))轉(zhuǎn)換為二進(jìn)制數(shù)(基數(shù)為:2(0或1))。

十進(jìn)制

十進(jìn)制數(shù)是一個十進(jìn)制數(shù),因為它的范圍從09,在09之間總共有10個數(shù)字。任何數(shù)字組合都是十進(jìn)制數(shù),例如:223585,1920,7等。

二進(jìn)制數(shù)

二進(jìn)制數(shù)是2的基數(shù),因為它是01。 01的任何組合都是二進(jìn)制數(shù),如:1001,10111111,101010等。

下面來看看看一些十進(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

將十進(jìn)制到二進(jìn)制轉(zhuǎn)換算法

步驟1:將數(shù)字除以(模運算符)2,并將余數(shù)存儲在數(shù)組中
步驟2:通過/(除法運算符)將數(shù)字除以2,
步驟3:重復(fù)步驟2,直到數(shù)字大于零

下面來看看看將十進(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

上一篇:C++指針下一篇:C++ this指針