题目:编写程序,把十进制正整数转换为n(n可以为2、8、16等等)进制数输出。
#include <iostream>
#include <malloc.h>
#include <cstring>
#include <string>
#define size 100
#define addsize 50
using namespace std;
typedef struct {
int *base;
int *top;
int stack_size;
}SqStack;
//初始化栈
void InitStack(SqStack &S) {
S.base = (int*)malloc(size * sizeof(int));
if (!S.base) {
cout << "初始化失败!" << endl;
exit(0);
}
S.top = S.base;
S.stack_size = size;
}
//入栈
bool PushStack(SqStack &S, int elem) {
//先要判断是否满栈
if (S.top - S.base >= S.stack_size) {
S.base = (int*)realloc(S.base, (size + addsize) * sizeof(int));
if (!S.base) {
return false;
}
S.top = S.base + S.stack_size;
S.stack_size += addsize;
}
*S.top++ = elem;
return true;
}
//出栈
bool Popstack(SqStack &S, int &elem) {
if (S.base == S.top) {
cout << "该栈为空,出栈失败!" << endl;
return false;
}
elem = *--S.top;
return true;
}
//判断是否为空栈
bool StackEmpty(SqStack S) {
if (S.base == S.top)
return true;
return false;
}
//进制转化的函数
void conversion() {
int ten, N, elem;
//用个字母来记录超过9的数
char a = 'A';
SqStack S;
InitStack(S);
cout << "输入你要转化的数(十进制)和你要转化成(N)进制的数(中间用空格分开):";
cin >> ten >> N;
elem = ten;
while (ten) {
PushStack(S, ten%N);
ten /= N;
}
cout << "10进制数"<<elem<<"转化的" << N << "进制数如下:" << endl;
while (!StackEmpty(S)) {
Popstack(S, elem);
if (elem > 9)
printf("%c", a + elem - 10);
else
cout << elem ;
}
}
int main(){
conversion();
return 0;
}