数制转换 C++

#include
using namespace std;
struct stack
{
char *base;
char *top;
};
void main()
{
char translate_char(int x);
int translate_num(char c);
int length(char *c);
int prompt();
__int64 num(char *c,int x);
int chars(__int64 x,int m,char an[40]);
int m,n,flag;
char x[40],an[40];
__int64 answer;
do
{
cout<<"请输入要转换的数,按回车(Enter)键结束"<cin>>x;
cout<<"输入要转换的数制类型(注意:本程序只支持在2-16进制数之间转换):"<cin>>m>>n;
if(m<2||m>16||n<2||n>16) {cout<<"对不起输入转换的数制类型不符合本程序要求;请重新输入:"<else if(m==n) {cout<<"请不要在相同的数制间转换"<else
{
cout<<"将"<if(m!=10&&n==10)
{
answer=num(x,m);
if(answer==-1) flag=prompt();
else {printf("%I64d\n",answer);flag=prompt();}
}
if(n!=10)
{
answer=num(x,m);
if(answer==-1) flag=prompt();
else
{
chars(answer,n,an);
cout<flag=prompt();
}
}
}
}while(flag);
}
char translate_char(int x)
{
char c;
if(x==0) c='0';
if(x==1) c='1';
if(x==2) c='2';
if(x==3) c='3';
if(x==4) c='4';
if(x==5) c='5';
if(x==6) c='6';
if(x==7) c='7';
if(x==8) c='8';
if(x==9) c='9';
if(x==10) c='a';
if(x==11) c='b';
if(x==12) c='c';
if(x==13) c='d';
if(x==14) c='e';
if(x==15) c='f';
return c;
}
int translate_num(char c)
{
int i;
if(c=='0') i=0;
if(c=='1') i=1;
if(c=='2') i=2;
if(c=='3') i=3;
if(c=='4') i=4;
if(c=='5') i=5;
if(c=='6') i=6;
if(c=='7') i=7;
if(c=='8') i=8;
if(c=='9') i=9;
if(c=='a') i=10;
if(c=='b') i=11;
if(c=='c') i=12;
if(c=='d') i=13;
if(c=='e') i=14;
if(c=='f') i=15;
if(c<'0'&&c>'9'&&c<'a'&&c>'f') i=-1;
return i;
}
int length(char *c)
{
int s=0;
while(*c!='\0') {s++;c++;}
return s;
}
int prompt()
{
int flag;
char c;
cout<<"是否还要继续进行下一个数制转换,是请输入y/Y,否则按其它任意键退出"<cin>>c;
if(c=='y'||c=='Y') flag=1;
else flag=0;
return flag;
}
__int64 num(char *c,int x)
{
int len,i,k;
len=length(c);
__int64 answer=0,t=1;
for(i=len-1;i>=0;i--)
{
k=translate_num(*(c+i));
if(k>=x||k==-1) {cout<<"错误的数据输入;请重新输入:"<answer=answer+k*t;
t=t*x;
}
return answer;
}
int chars(__int64 x,int m,char an[])
{
stack p;
int k,i=0;
p.base=p.top=(char*)malloc(40*sizeof(char));
if(!p.base) return 0;
do
{
k=x%m; *p.top++=translate_char(k);//cout<<*(p.top-1);
x=x/m;
}while(x);
while(p.base!=p.top)
{*(an+i++)=*--p.top;}
*(an+i)='\0';
return 1;
}

相关文档
最新文档