- 更多内容及实时更新请关注我的个人技术文档分享:www.ywenrou.cn
- 如需引用请注明出处,谢谢!
利用栈进行十进制转换二进制
#include<iostream>
#include<cstdlib>
using namespace std;
#define max 10
struct storage
{
int a[max];
int top;
};
void initstorage(struct storage *S)
{
S->top = -1;
}
void inserstorage(struct storage*S, int b)
{
if (S->top!=max-1)
{
S->top++;
S->a[S->top] = b;
}
}
void pop(struct storage*S, int *b)
{
int c = S->top;
if (S->top != -1)
{
for (size_t i = 0; i <= c; i++)
{
b[i] = S->a[S->top];
S->top--;
}
}
}
int main()
{
struct storage *S;
S = (struct storage *)malloc(sizeof(struct storage));
int i;
int a;
int count;
int result[10] = {0};
cout << "=====欢迎使用进制转换======" << endl;
begin:cout << "请输入数(十进制):";
cin >> i;
initstorage(S);
cout << "请输入需要转换的进制(1-10之间):";
cin >> a;
while (i!=0)
{
inserstorage(S, i % a);
i = i / a;
}
cout << "转换的"<<a<<"进制为:";
count = S->top;
if(S->top!=-1)
{
pop(S,result);
}
for (size_t i = 0; i <= count; i++)
{
cout << result[i];
}
cout << endl;
goto begin;
return 0;
}