C++ 中十進位制轉二進位制的程式
給定一個十進位制數作為輸入,任務是將給定的十進位制數轉換為二進位制數。
計算機中的十進位制數以基 10 表示,而二進位制數以基 2 表示,因為它只有兩個二進位制數字 0 和 1,而十進位制數可以是 0-9 之間的任意數字。
要將十進位制數字轉換為二進位制數字,請遵循以下步驟:
- 首先用轉換數字的基值除以給定數字,例如將 42 除以 2,因為我們需要將 42 轉換為二進位制數字,其基值為 2,然後獲得商並存儲。如果餘數為 0,則將位儲存為 0,否則為 1。
- 用二進位制數的基值(2)除以獲得的商,並繼續儲存位。
- 繼續將儲存的位向右移
- 重複此步驟,直到剩餘的餘數不可再被整除
以下是將十進位制數轉換為二進位制數的示意圖。
示例
Input-: 42 Divide the 42 with base 2 : 42 / 2 = 0 (remainder) 21(quotient) Divide quotient with base: 21 / 2 = 1(remainder) 10(quotient) Divide quotient with base: 10 / 2 = 0(remainder) 5(quotient) Divide quotient with base: 5 / 2 = 1(remainder) 2(quotient) Divide quotient with base: 2 / 2 = 0(remainder) 1(quotient) Now reverse the bits to obtain final value. Output-: 101010
演算法
Start Step 1-> declare function to convert decimal to binary int convert(int num) Loop For int i = 31 i >= 0 i— Set int k = num >> i If (k & 1) Print "1" End Else Print "0" End End Step 2-> In main() Declare and set int num = 42 Call convert(num) Stop
示例
#include <iostream> using namespace std; //convert decimal to binary int convert(int num) { for (int i = 31; i >= 0; i--) { int k = num >> i; if (k & 1) cout << "1"; else cout << "0"; } } int main() { int num = 42; convert(num); }
輸出
如執行以上程式碼,它將生成以下輸出
00000000000000000000000000101010
廣告