题目要求
将一个非负十进制整数N转换为二进制、八进制或十六进制。
代码演示
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define MAXSIZE 100
#define ERROR 0
#define OK 1
#define OVERFLOW 1
typedef struct {
int* base;
int* top;
int stacksize;
}SqStack;
void Push(SqStack& S, int e) {
if (S.top - S.base == S.stacksize) return ERROR;
*S.top++ = e;
return OK;
}
void Pop(SqStack& S, int &e) {
if (S.top == S.base) return ERROR;
e = *--S.top;
return OK;
}
void InitStack(SqStack& S) {
S.base = new int[MAXSIZE];
if (!S.base) exit(OVERFLOW);
S.top = S.base;
S.stacksize = MAXSIZE;
return OK;
}
void eight(int N) {
SqStack S;
InitStack(S);
while (N)
{
Push(S, N % 8);
N = N / 8;
}
while (S.top - S.base != 0)
{
int e;
Pop(S, e);
printf("%d", e);
}
}
void two(int N) {
SqStack S;
InitStack(S);
while (N)
{
Push(S, N % 2);
N = N / 2;
}
while (S.top - S.base != 0)
{
int e;
Pop(S, e);
printf("%d", e);
}
}
void sixteen(int N) {
SqStack S;
InitStack(S);
while (N)
{
Push(S, N % 16);
N = N / 16;
}
while (S.top - S.base != 0)
{
int e;
Pop(S, e);
if (e > 9) {
switch (e)
{
case 10:
printf("A");
break;
case 11:
printf("B");
break;
case 12:
printf("C");
break;
case 13:
printf("D");
break;
case 14:
printf("E");
break;
case 15:
printf("F");
break;
}
}
else
{
printf("%d", e);
}
}
}
int main() {
int a;
printf("请输入一个数:");
scanf_s("%d", &a);
printf("%d的八进制为:",a);
eight(a);
printf("\n");
printf("%d的二进制为:",a);
two(a);
printf("\n");
printf("%d的十六进制为:",a);
sixteen(a);
}