原题是正整数的转换,只能练习到栈。但小数部分恰好是队列实现的,所以加上小数部分,可以一道题练习一整章的核心知识点
Stack.h
#pragma once
#include<iostream>
using namespace std;
class Stack {
public:
int* elements;
int maxSize;
int top;
Stack(int size = 20) {
maxSize = size;
elements = new int[maxSize];
top = -1;
}
void overflow() {
int* arr;
arr = new int[maxSize * 2];
for (int i = 0; i <= top; i++) {
arr[i] = elements[i];
}
int* p = elements;
elements = arr;
maxSize *= 2;
delete[]p;
}
void push(int elem) {
if (top == maxSize - 1) {
overflow();
}
elements[++top] = elem;
}
bool pop(int& e) {
bool res = true;
if (top == -1) {
res = false;
}
else {
e = elements[top--];
}
return res;
}
};
Queue.h
#pragma once
#include<iostream>
using namespace std;
class QNode {
public:
int data;
QNode* next;
};
class Queue {
public:
QNode* front;
QNode* rear;
Queue() {
front = nullptr;
rear = nullptr;
}
void enqueue(int e) {
QNode* s = new QNode();
s->data = e;
if (front == nullptr) {
front = s;
rear = s;
}
else {
s->next = rear->next;
rear->next = s;
rear = s;
}
}
bool dequeue(int& e) {
bool res = true;
if (front == nullptr) {
res = false;
}
else {
e = front->data;
QNode* p;
p = front;
front = front->next;
delete p;
}
return res;
}
};
MyTool.h
#pragma once
#include"Queue.h"
#include"Stack.h"
class MyTool {
public:
static void transform(double data,int base) {
if (data <= 0) {
cerr << "Please input a number greater than zero!" << endl;
exit(1);
}
Stack s; //stack处理整数部分 ,queue处理小数部分
Queue que;
int part_int;
part_int = (int)data;
double part_decimal;
part_decimal = data - part_int;
//先分离出整数部分,处理整数部分
int elem;
while (part_int != 0) {
elem = part_int % base;
s.push(elem);
part_int /= base;
}
//接下来处理小数部分
int index = 0;//记录数位,限制数位大小,避免无限小数导致异常
while (part_decimal > 0 && index < 10) {
//10位小数以内,不考虑浮点数下溢情况
part_decimal *= base;
elem = (int)part_decimal;
que.enqueue(elem);
part_decimal -= elem;
index++;
}
//输出这个数
//不用ABC这些字母了,所以中间空出一个,表示数位之间间隔
while (s.pop(elem)) {
cout << elem << " ";
}
cout << ".";
while (que.dequeue(elem)) {
cout << elem << " ";
}
cout << endl;
}
};
main.cpp
#include"MyTool.h"
int main() {
double a;
int base;
cout << "Input a double decimal:" << endl;
cin >> a;
cout << "Input a base:" << endl;
cin >> base;
MyTool::transform(a, base);
return 0;
}
来源:https://www.cnblogs.com/SlowIsFast/p/12636324.html