C++ 十進位制轉換為十六進位制的程式
給定一個十進位制數作為輸入,任務是將給定的十進位制數轉換為十六進位制數。
計算機中的十六進位制數以 16 為基數表示,十進位制數以 10 為基數表示,並用 0 到 9 的值表示,而十六進位制數的數字從 0 到 15 開始,其中 10 表示為 A,11 表示為 B,12 表示為 C,13 表示為 D,14 表示為 E,15 表示為 F。
要將十進位制數轉換為十六進位制數,請按照以下步驟操作:
- 首先,將給定數字除以轉換數字的基數,例如,將 6789 除以 16,因為我們需要將 6789 轉換為以 16 為基數的十六進位制數,然後獲得商並將其儲存。如果餘數在 0 到 9 之間,則按原樣儲存;如果餘數在 10 到 15 之間,則將其轉換為 A 到 F 的字元形式。
- 將獲得的商除以十六進位制數的基數 16,並繼續儲存位。
- 對儲存的位進行右移操作。
- 重複此步驟,直到餘數不可再除。
以下是將十進位制數轉換為十六進位制數的圖形表示。
示例
Input-: 6789 Divide the 6789 with base 16 : 6789 / 16 = 5 (remainder) 424(quotient) Divide quotient with base: 424 / 16 = 8(remainder) 26(quotient) Divide quotient with base: 26 / 16 = 10(remainder) 1(quotient) Now reverse the remainder obtained for final hexadecimal value. Output-: 1A85
演算法
Start Step 1-> Declare function to convert decimal to hexadecimal void convert(int num) declare char arr[100] set int i = 0 Loop While(num!=0) Set int temp = 0 Set temp = num % 16 IF temp < 10 Set arr[i] = temp + 48 Increment i++ End Else Set arr[i] = temp + 55 Increment i++ End Set num = num/16 End Loop For int j=i-1 j>=0 j— Print arr[j] Step 2-> In main() Set int num = 6789 Call convert(num) Stop
示例
#include<iostream> using namespace std; //convert decimal to hexadecimal void convert(int num) { char arr[100]; int i = 0; while(num!=0) { int temp = 0; temp = num % 16; if(temp < 10) { arr[i] = temp + 48; i++; } else { arr[i] = temp + 55; i++; } num = num/16; } for(int j=i-1; j>=0; j--) cout << arr[j]; } int main() { int num = 6789; cout<<num<< " converted to hexadeciaml: "; convert(num); return 0; }
輸出
如果我們執行以上程式碼,它將生成以下輸出:
6789 converted to hexadeciaml: 1A85
廣告