题目描述
对于任意十进制数转换为k进制,包括整数部分和小数部分转换。整数部分采用除k求余法,小数部分采用乘k取整法例如x=19.125,求2进制转换
整数部分19, 小数部分0.125 19 / 2 = 9 … 1 0.125 * 2 = 0.25 … 0 9 / 2 = 4 … 1 0.25 * 2 = 0.5 … 0 4 / 2 = 2 … 0 0.5 * 2 = 1 … 1 2 / 2 = 1 … 0 1 / 2 = 0 … 1
所以整数部分转为 10011,小数部分转为0.001,合起来为10011.001
提示整数部分可用堆栈,小数部分可用队列实现
注意:必须按照上述方法来实现数制转换,其他方法0分
输入
第一行输入一个t,表示下面将有t组测试数据。
接下来每行包含两个参数n和k,n表示要转换的数值,可能是非整数;k表示要转换的数制,1<k<=16
输入样例:
2
19.125 2
15.125 16
输出
对于每一组测试数据,每行输出转换后的结果,结果精度到小数点后3位
输出样例:
10011.001
F.200
代码
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
char arr[6] = {'A','B','C','D','E','F'};
string ToInteger(int zs, int scale){ //整数部分的进制转换
string s = "";
stack<int> sta;
int remainder; //余数
while(zs != 0){
remainder = zs % scale;
zs /= scale;
sta.push(remainder);
}
int k;
while(!sta.empty()){
k = sta.top();
if(k >= 10){ //如果余数>=10,根据进制用对应ABCDEF表示
s += arr[k-10];
}else{
s += (char)('0' + k);
}
sta.pop();
}
return s;
}
string ToDecimals(double xs, int scale){ //小数部分的进制转换
string s = "";
double k;
int r = 0;
queue<int> que;
while(xs != r){ //当此数无小数部分时结束
xs -= r;
xs *= scale;
r = xs/1;
que.push(r);
}
int v;
while(!que.empty()){
v = que.front();
if(v >= 10){
s += arr[v-10];
}else{
s += (char)('0' + v);
}
que.pop();
}
return s;
}
int main()
{
int t,zs,scale,len;
double num,xs;
string a,b;
cin >> t;
while(t--){
cin >> num >> scale;
zs = num/1; //得到整数部分
xs = num - zs; //得到小数部分
a = ToInteger(zs,scale);
b = ToDecimals(xs,scale);
len = b.length();
cout << a << '.';
if(len < 3){ //保留三位小数
for(int i = len; i < 3; i++){
b[i] = '0';
}
}
cout << b[0] << b[1] << b[2] << endl;
}
return 0;
}