C++ 中八進位制到十進位制轉換程式


給定八進位制數作為輸入,任務是將給定的八進位制數轉換為十進位制數。

計算機中的十進位制數以 10 為基數表示,而八進位制數以 8 為基數表示,從數字 0 到 7 開始,而十進位制數可以是 0 到 9 之間的任何數字。

若要將八進位制數轉換為十進位制數,請執行以下步驟

  • 我們將從右到左透過餘數提取數字,然後用從 0 開始並增加 1 直到(數字數)-1 的次冪乘以它
  • 由於我們需要進行八進位制到二進位制的轉換,因此指數的基數將為 8,因為八進位制有 8 個基數。
  • 將給定輸入的數字與基數和次冪相乘,並存儲結果
  • 將所有乘積值相加以獲得最終結果,最終結果將是十進位制數。

下面是將八進位制數轉換為十進位制數的示意圖。

示例

Input-: 451
   1 will be converted to a decimal number by -: 1 X 8^0 = 1
   5 will be converted to a decimal number by -: 5 X 8^1 = 40
   4 will be converted to a decimal number by -: 4 X 8^2 = 256
Output-: total = 0 + 40 + 256 = 10

演算法

Start
Step 1-> declare function to convert octal to decimal
   int convert(int num)
      set int temp = num
      set int val = 0
      set int base = 1
      Set int count = temp
      Loop While (count)
         Set int digit = count % 10
         Set count = count / 10
         Set val += digit * base
         Set base = base * 8
      End
      return val
step 2-> In main()
   set int num = 45
   Call convert(num)
Stop

示例

 現場演示

#include <iostream>
using namespace std;
//convert octal to decimal
int convert(int num) {
   int temp = num;
   int val = 0;
   int base = 1;
   int count = temp;
   while (count) {
      int digit = count % 10;
      count = count / 10;
      val += digit * base;
      base = base * 8;
   }
   return val;
}
int main() {
   int num = 45;
   cout <<"after conversion value is "<<convert(num);
}

輸出

如果我們執行以上程式碼,它會生成以下輸出

after conversion value is 37

更新時間:18-Oct-2019

167 次檢視

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.