|
发表于 2013-7-15 20:49:37
|
显示全部楼层
#include<iostream>
#include<stack>
#include<string>
using namespace std;
char s1[200];
int trans_ten(int x,int j)
{
int k=0;
while(x)
{
s1[k++]=x%j+48;
x/=j;
}
return k;
}
int trans_two_ten(string s)
{
int ans=0,k=1;
for(int i=s.length()-1;i>=0;i--)
{
ans+=(s[i]-48)*k;
k*=2;
}
return ans;
}
int trans_two_sixteen(string s)
{
int k=1,rev=1,bit=0,cnt=0;
for(int i=s.length()-1;i>=0;i--)
{
if(k%4)
{
bit+=(s[i]-48)*rev;
rev*=2;
k++;
}
else
{
bit+=(s[i]-48)*rev;
rev=1;
if(bit<10)
s1[cnt++]=bit+48;
else
s1[cnt++]=bit+55;
bit=0;
k++;
}
}
if(k%4!=1)
{
s1[cnt++]=bit+48;
}
s1[cnt]='\0';
return cnt;
}
int trans_two_eight(string s)
{
int k=1,rev=1,bit=0,cnt=0;
for(int i=s.length()-1;i>=0;i--)
{
if(k%3)
{
bit+=rev*(s[i]-48);
rev*=2;
k++;
}
else
{
bit+=rev*(s[i]-48);
rev=1;
k++;
s1[cnt++]=bit+48;
bit=0;
}
}
if(k%3!=1)
{
s1[cnt++]=bit+48;
}
s1[cnt]=0;
return cnt;
}
int main()
{
cout<<"进制转化系统——made by 四季如春"<<endl<<endl;
cout<<"十进制转化为二进制输入1"<<endl;
cout<<"十进制转化为八进制输入2"<<endl;
cout<<"二进制转化为十进制输入3"<<endl;
cout<<"二进制转化为十六进制输入4"<<endl;
cout<<"二进制转化为八进制输入5"<<endl;
cout<<"输入0退出"<<endl;
int n;
while(cin>>n&&n!=0)
{
memset(s1,'\0',sizeof(s1));
if(n==1)
{
int x;
cout<<"请输入一个十进制数"<<endl;
cin>>x;
cout<<"对应的二进制数为:";
int len=trans_ten(x,2);
for(int i=len-1;i>=0;i--)
cout<<s1[i];
cout<<endl;
}
if(n==2)
{
int x;
cout<<"请输入一个十进制数"<<endl;
cin>>x;
cout<<"对应的八进制数为:";
int len=trans_ten(x,8);
for(int i=len-1;i>=0;i--)
cout<<s1[i];
cout<<endl;
}
if(n==3)
{
string s;
cout<<"请输入一个二进制数"<<endl;
cin>>s;
cout<<"对应的十进制数为:"<<trans_two_ten(s)<<endl;
}
if(n==4)
{
string s;
cout<<"请输入一个二进制数"<<endl;
cin>>s;
cout<<"对应的十六进制的数为:";
int cnt=trans_two_sixteen(s);
for(int i=cnt-1;i>=0;i--)
cout<<s1[i];
cout<<endl;
}
if(n==5)
{
string s;
cout<<"请输入一个二进制数"<<endl;
cin>>s;
cout<<"对应的八进制数为:";
int cnt=trans_two_eight(s);
for(int i=cnt-1;i>=0;i--)
{
cout<<s1[i];
}
cout<<endl;
}
}
return 0;
} |
|