一、题目描述
对于任意十进制数转换为k进制,包括整数部分和小数部分转换。整数部分采用除k求余法,小数部分采用乘k取整法例如x=19.125,求2进制转换
整数部分19,
19 / 2 = 9 … 1
9 / 2 = 4 … 1
4 / 2 = 2 … 0
2 / 2 = 1 … 0
1 / 2 = 0 … 1
小数部分0.125
0.125 * 2 = 0.25 … 0
0.25 * 2 = 0.5 … 0
0.5 * 2 = 1 … 1
所以整数部分转为 10011,小数部分转为0.001,合起来为10011.001
提示整数部分可用堆栈,小数部分可用队列实现
注意:必须按照上述方法来实现数制转换,其他方法0分
二、输入与输出
1.输入
第一行输入一个t,表示下面将有t组测试数据。
接下来每行包含两个参数n和k,n表示要转换的数值,可能是非整数;k表示要转换的数制,1<k<=16
2
19.125 2
15.125 16
2.输出
对于每一组测试数据,每行输出转换后的结果,小数部分保留3位
10011.001
F.200
三、参考代码
#include <iostream>
#include <stack>
#include <string>
#include<queue>
#include<math.h>
#include<iomanip>
using namespace std;
int main() {
int sum;
cin >> sum;
double num, xiaoshu;
int k, zhengshu, x = 0;
//char key[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
while (sum--)
{
stack<int> s;
queue<int> q;
cin >> num >> k;
zhengshu = (int)num;
xiaoshu = num - zhengshu;
while (zhengshu!=0)
{
x = zhengshu % k;
zhengshu /= k;
s.push(x);
}
while (!s.empty())
{
if (k >= 10) {
if (s.top() >= 10) {
char ch = s.top() - 10 + 'A';
cout << ch;
}
else
{
cout << s.top();
}
}
else cout << s.top();
s.pop();
}
cout << ".";
int j = 3;
while (j--)
{
x = (int)(xiaoshu * k);
xiaoshu = xiaoshu * k - x;
q.push(x);
}
for (int i = 0; i < 3; i++) {
int f = q.front();
if (!q.empty())
{
if (k >= 10) {
if (f >= 10) {
char ch = f - 10 + 'A';
cout << ch;
}
else
{
cout << f;
}
}
else cout << f;
q.pop();
}
else cout << "0";
}
cout << endl;
}
return 0;
}
/**********************************************************************
Problem: 1077
Language: C++
Result: AC
Time:7 ms
Memory:2224 kb
**********************************************************************/