1)转换为八进制(栈实现)
#include<iostream>
using namespace std;
#define MAXSIZE 100
typedef struct
{
int *base;
int *top;
}SqStack;
void InitStack(SqStack &S)//初始化
{
S.base=new int [MAXSIZE];
S.top=S.base;
}
int StackEmpty(SqStack S)//判空
{
if(S.top == S.base)
return 1;
else return 0;
}
void push(SqStack &S,int e)//入栈
{
if(S.top-S.base==MAXSIZE)
{
cout<<"该栈储存空间已满!!!"<<endl;
}
*S.top++=e;
}
void pop(SqStack &S,int &e)//出栈
{
e=*--S.top;
}
int main()
{
int num,e;
SqStack S;
InitStack(S);
cout<<"请输入一个数 :";
cin>>num;
while(num){
push(S,num%8);
num/=8;
}
cout<<"转化为八进制为:";
while(!StackEmpty(S))
{
pop(S,e);
cout<<e;
}
cout<<endl;
return 0;
}
2)转换为八进制 (递归实现)
#include<iostream>
using namespace std;
int num;
void change(int a)
{
if(a!=0)
{
change(a/8);
cout<<a%8;
}
}
int main()
{
cout<<"请输入一个数:";
cin>>num;
cout<<"该数转换为8进制为:";
change(num);
return 0;
}
3)转换为n(2-10)进制
//递归实现
#include<iostream>
using namespace std;
int t,num;
void change(int a,int t)
{
if(a!=0)
{
change(a/t,t);
cout<<a%t;
}
}
int main()
{
cout<<"请输入一个数:";
cin>>num;
cout<<"请输入要转换的进制:";
cin>>t;
cout<<"该数转换为"<<t<<"进制为:";
change(num,t);
return 0;
}
//栈实现
#include<iostream>
using namespace std;
#define MAXSIZE 100
typedef struct
{
int *base;
int *top;
}SqStack;
void InitStack(SqStack &S)//初始化
{
S.base=new int [MAXSIZE];
S.top=S.base;
}
int StackEmpty(SqStack S)//判空
{
if(S.top == S.base)
return 1;
else return 0;
}
void push(SqStack &S,int e)//入栈
{
if(S.top-S.base==MAXSIZE)
{
cout<<"该栈储存空间已满!!!"<<endl;
}
*S.top++=e;
}
void pop(SqStack &S,int &e)//出栈
{
e=*--S.top;
}
int main()
{
int num,e,t;
SqStack S;
InitStack(S);
cout<<"请输入一个数 :";
cin>>num;
cout<<"请输入要转换的进制:";
cin>>t;
while(num){
push(S,num%t);
num/=t;
}
cout<<"该数转换为"<<t<<"进制为:";
while(!StackEmpty(S))
{
pop(S,e);
cout<<e;
}
cout<<endl;
return 0;
}
4)负数的进制转换
题目 : https://www.luogu.org/problem/show?pid=1017
-15 转 -2 进制 为 110001
#include<iostream>
#define SIZE 200005
using namespace std;
char b[SIZE];
int main()
{
long long n,m,t=0,k=0;
cin>>n>>m;
cout<<n<<"=";
while(n!=0){
t=n%m;
n/=m;
if(t<0) {
t-=m;n+=1;
}
if(t<10){
b[k++]=t+'0';
}
else
{
b[k++]=t-10+'A';
}
}
for(int i=k-1;i>=0;i--)
cout<<b[i];
cout<<"(base"<<m<<")";
return 0;
}