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


輸入一個二進位制數之後,任務是將給定的二進位制數轉換成十進位制數。

計算機中的十進位制數以 10 為底,而二進位制數則以 2 為底,因為它只有兩個二進位制數字 0 和 1,而十進位制數可以是從 0 到 9 的任何數字。

要將二進位制數轉換為十進位制數,我們要從右向左提取數字透過餘數,然後從 0 開始乘以 2 的次方,並且直到 (數字數) – 1 時增加 1,同時將乘積值相加以得到最終十進位制數。

下面是將二進位制數轉換成十進位制數的圖片表示。

示例

Input-: 1010
   0 will be converted to a decimal number by -: 0 X 2^0 = 0
   1 have corresponding binary equivalent of 3 digit -: 1 X 2^1 = 2
   0 have corresponding binary equivalent of 3 digit -: 0 X 2^2 = 0
   1 have corresponding binary equivalent of 3 digit -: 1 X 2^3 = 8
Output-: total = 0 + 2 + 0 + 8 = 10

演算法

Start
Step1-> Declare function to convert binary to decimal
   int convert(string str)
   set string n = str
   set int val = 0
   set int temp = 1
   set int len = n.length()
   Loop For int i = len - 1 i >= 0 i—
      IF n[i] == '1'
         Set val += temp
      End
      Set temp = temp * 2
   End
   return val
Step 2-> In main()
   Set string val = "11101"
   Call convert(val)
Stop

示例

 即時演示

#include <iostream>
#include <string>
using namespace std;
//convert binary to decimal
int convert(string str) {
   string n = str;
   int val = 0;
   int temp = 1;
   int len = n.length();
   for (int i = len - 1; i >= 0; i--) {
      if (n[i] == '1')
      val += temp;
      temp = temp * 2;
   }
   return val;
}
int main() {
   string val = "11101";
   cout<<val<<" after converion into deciaml : "<<convert(val);
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

11101 after converion into deciaml : 29

更新於:2019 年 10 月 18 日

300 次瀏覽

開啟你的職業生涯

完成本課程成為認證會員

開始學習
廣告
© . All rights reserved.