实现堆栈输入输出,十进制转八进制和十六进制
1.入栈
代码如下(示例):
void intput(ElemType a[], int& top,ElemType item)
{
if (top == (N - 1))//判断栈满
{
cout << "堆栈满" << endl;
return;
}
top++;
a[top]=item;
}
2.出栈
代码如下(示例):
void output(ElemType a[], int& top, ElemType& item)
{
if (top == (-1))//判断栈空
{
cout << "堆栈空" << endl;
return;
}
item = a[top];
top--;
}
3.十进制转八进制
100/8=12…4
12 / 8=1…4
1 / 8=0…1
100的八进制为144
只需要把每次的余数保留就是得到的结果,一直除到商为0
void DecimaltoOctal(int num)
{
int a[N];
int top=-1;
do {
top++;
a[top] = num % 8;
num = num / 8;
} while (num != 0);
cout << "八进制:";
do {
cout << a[top--];
} while (top!=-1);
}
4.八进制转十六进制
八进制转十六进制 与 十进制转八进制 同理
只需要把每次的余数保留就是得到的结果,一直除到商为0
但在输出的时候十六进制:
A=10 B=11 … F=15 稍微改动即可
void DecimaltoHexadecimal(int num)
{
int a[N];
int top = -1;
do {
top++;
a[top]=num % 16;
num = num / 16;
} while (num != 0);
cout << "十六进制:";
do {
if (a[top] > 9)
{
switch (a[top]) {
case 10:
cout << 'A'; break;
case 11:
cout << 'B'; break;
case 12:
cout << 'C'; break;
case 13:
cout << 'D'; break;
case 14:
cout << 'E'; break;
default:
cout << 'F'; break;
}
}
else
{
cout << a[top];
}
top--;
} while (top != -1);
}
5.附上源码
#include<iostream>
using namespace std;
#define N 100
typedef int ElemType;
void intput(ElemType a[], int& top,ElemType item)
{
if (top == (N - 1))//判断栈满
{
cout << "堆栈满" << endl;
return;
}
top++;
a[top]=item;
}
void output(ElemType a[], int& top, ElemType& item)
{
if (top == (-1))//判断栈空
{
cout << "堆栈空" << endl;
return;
}
item = a[top];
top--;
}
void DecimaltoOctal(int num)
{
int a[N];
int top=-1;
do {
top++;
a[top] = num % 8;
num = num / 8;
} while (num != 0);
cout << "八进制:";
do {
cout << a[top--];
} while (top!=-1);
}
void DecimaltoHexadecimal(int num)
{
int a[N];
int top = -1;
do {
top++;
a[top]=num % 16;
num = num / 16;
} while (num != 0);
cout << "十六进制:";
do {
if (a[top] > 9)
{
switch (a[top]) {
case 10:
cout << 'A'; break;
case 11:
cout << 'B'; break;
case 12:
cout << 'C'; break;
case 13:
cout << 'D'; break;
case 14:
cout << 'E'; break;
default:
cout << 'F'; break;
}
}
else
{
cout << a[top];
}
top--;
} while (top != -1);
}
int main()
{
ElemType a[N];
int top = -1;
ElemType item;
DecimaltoOctal(100);
DecimaltoHexadecimal(100);
cout << ' ' << endl;
cout<<"输入需进栈数量:";
int n;
cin >> n;
for (int i = 0;i < n;i++)
{
cin >> item;
intput(a, top, item);
}
cout << "输入需退栈数量:";
cin >> n;
for (int i = 0;i < n;i++)
{
output(a, top, item);
cout<<item<<" ";
}
return 0;
}
6.运行结果
八进制:144十六进制:64
输入需进栈数量:3
1 2 3
输入需退栈数量:3
3 2 1