1、十进制转其他进制
引出此通用方法,但是只能用与十进制转10以内进制;eg:16进制有ABXDEF
#include<iostream>
#include<vector>
using namespace std;
void Convert(int n, int x)
{
vector<int> answer;
if(n==0)
{
cout<<0<<endl;
return;
}
while(n!=0)
{
answer.push_back(n%x);
n /=x;
}
for(int i=answer.size()-1;i>=0;--i)
{
cout<<answer[i];
}
cout<<endl;
}
int main()
{
int n;
while(cin>>n)
{
Convert(n,8);
}
return 0;
}
真正通用
#include<iostream>
#include<vector>
using namespace std;
char inttochar(int n)
{
if(n<10)
return n+'0';
else
return n-10+'A';
}
void Convert(int n, int x)
{
vector<char> answer;
if(n==0)
{
cout<<0<<endl;
return;
}
while(n!=0)
{
answer.push_back(inttochar(n%x));
n /=x;
}
for(int i=answer.size()-1;i>=0;--i)
{
cout<<answer[i];
}
cout<<endl;
}
int main()
{
int n;
while(cin>>n)
{
Convert(n,16);
}
return 0;
}
2.其他进制转化为十进制
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int CharToInt(char c)
{
if(c>='0' && c<='9')
return c-'0';
else
return c-'A'+10;
}
void Convert(string str,int x)
{
int number =0;
for(int i=0;i<str.size();++i)
number = number*x + CharToInt(str[i]);//12345利用10进制的求法思考
cout<<number<<endl;
}
int main()
{
string str;
while(cin>>str)
{
str = str.substr(2);
Convert(str,16);//此处16代表str的类型,不是要转化的类型
}
return 0;
}
3.M进制转化为N进制:利用十进制做中间量
#include<iostream>
#include<string>
#include<vector>
using namespace std;
char IntToChar(int n)
{
if(n<10)
return n+'0';
else
return n-10+'A';
}
long long CharToInt(char c)
{
if(c>='0' && c<='9')
return c-'0';
else
return c-'A'+10;
}
long long ConvertToTen(string str, int m)
{
long long number =0;
for(int i=0;i<str.size();++i)
number = number*m + CharToInt(str[i]);
return number;
}
void ConvertToN(long long number ,int N)
{
vector<char> v;
while(number!=0)
{
v.push_back(IntToChar(number%N));
//cout<<v[v.size()-1]<<endl;
number /=N;
}
for(int i=v.size()-1;i>=0;--i)
cout<<v[i];
cout<<endl;
}
int main()
{
int M,N;
while(cin>>M && cin>>N)
{
string str;
cin>>str;
long long number = ConvertToTen(str,M);//M进制转化为十进制
//cout<<number<<endl;
ConvertToN(number,N);//十进制转为N进制
}
return 0;
}