將P進制數轉換成Q進制數需要兩個步驟:
- 將P進制數轉換成十進制數;
- 將十進制數轉換成Q進制數.
下面是我寫的實現:
/* 任意進制的轉換需要兩個步驟:
* (1)將P進制數轉換成十進制數;
* (2)將十進制數轉換成Q進制數。
*/
#include <iostream>
#include <string>
#include <stack>
using namespace std;
const char d[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/*******************************************************************************************
* 功能: 將P進制數轉換成Q進制數
* -x : 需要轉換的P進制數
* -P : P進制數
* -Q : Q進制數
*******************************************************************************************/
void PtoQ(int x, int P, int Q) {
int decimal = 0, product = 1;
// 將P進制數轉換成十進制數
while(x) {
decimal += (x % P) * product;
product *= P;
x /= P;
}
// 除基取餘法:將十進制數轉換成Q進制數
stack<int> s; // 用棧存放餘數
do{ // 注意此處不能用while(),因爲當剛好是0的時候就會出錯!
s.push(decimal % Q);
decimal /= Q;
}while(decimal != 0);
while(!s.empty()) {
cout << d[s.top()];
s.pop();
}
cout << endl;
}
int main()
{
int P, Q;
cin >> P >> Q; // 將P進制數轉換成Q進制數
int x;
cin >> x; // 輸入要轉換的P進制數
PtoQ(x, P, Q); // 轉換
return 0;
}