将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;
}