實現任意兩進制之間的轉換

 核心思想爲:將舊的進制先轉換爲十進制的數字,然後再將十進制的數字轉換爲新的進制。

 例如:將7進制的23轉換爲9進制的數字爲??

7進制-->10進制   23 = 3*7^0 + 2 * 7^1 = 3 +14 = 17;

10進制-->9進制   17 % 9 = 8; 17/9 = 1;

                             1 %9 = 1;  1/9 = 0;

 核心公式爲:x = n % m ;   n = n / m; (n爲十進制數,m爲將要轉換的進制數,x爲取餘後的數)

                      最後將餘數反向輸出,也可以利用棧的“先進後出”的特點進行對餘數的保存。


代碼如下:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <queue>
using namespace std;

int main()
{
    int old,now;//old代表本來所屬禁止,now代表將要轉換的進制 
    string data;//使用data來存放原進制類型的數據
    char data_new[100];//存放要轉換的進制的數據 
    cin >> old >> data >> now;

    int num_10 = 0;//作爲中間變量,存儲動態的中間十進制 
    int value = 1;//將value作爲權重 

    for(int i=data.length()-1;i>=0;i--){//將原進制轉換爲十進制 
        int temp=0;
        if(data[i]>='0'&&data[i]<='9')
        {
			temp=data[i]-'0'; 
		}
        else
		{
            temp=data[i]-'A'+10;//求出該位對應的10進制數
		}
        num_10 += temp*value; //數字加權重
        value*=old;   
    }
    cout<<"10進制數字爲:"<< num_10 <<endl;

    int new_cnt=0;//存儲新類型中字符的個數 
    do{
        int temp=0;
        temp=num_10%now;
        num_10/=now;
        if(temp>=10)
            data_new[new_cnt++]=temp-10+'A';
        else
            data_new[new_cnt++]=temp+'0';           

    }while(num_10);

    cout << now <<"進制數據爲:";
    for(int i= new_cnt-1;i>=0;i--)
        cout<<data_new[i];
    cout<<endl;  
    return 0;
} 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章