进制转换非常常见,如十进制转化为十六进制(n进制),八进制转划为十六进制,这里写几种进制转化,其余类似套用即可

一 . 十进制转化为其他进制(n进制)

十进制转化为n进制,则是将数不停对n求余,余数倒序输出,这非常符合栈stack这种结构,数据先进后出

附上十进制转化为十六进制的代码

#include<iostream>
#include<stack>

using namespace std;

int main()
{
	int n,m;
	char c;
	stack<int> s;  //定义一个栈结构 
	cin>>n;
    if(n==0)  cout<<0;  //0的情况一定不要忘记
    else{
	       while(n)
	       {//循环里的16可以替换 
		       m=n%16;  //m表示余数     
		       s.push(m);  //将余数压入栈 
		       n=n/16;
	       }
	       while(!s.empty())  //当栈不为空时,就输出结果
	       {
		       if(s.top()>=10) {  //若栈顶大于十,则根据ACII码输出对应字母 ,还有第二钟方法
			   char c=s.top()-9+64;
			   cout<<c;
               }
		       else cout<<s.top();
		       s.pop();  //将已经用过的数弹出栈 
	       }
         }
	 return 0;
}


 

法二:

#include<iostream>
#include<stack>

using namespace std;

int main(){
	char s[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    //避免后期的ACII转码,比较方便
	int n;
	stack<char> s;  //字符型
	cin>>n;
	if(n==0)   cout<<0;
	else{
		    while(n)
            {
			    s.push(s[n%16]);
			    n /= 16;
		    }
		    while(!s.empty())
           {
			    cout<<s.top();
			    s.pop();
		   }
	     }
	
	return 0;
} 

十六进制转为十进制

#include<iostream>
#include<string>

using namespace std;

int main()
{
	string s;
	while(cin>>s)
	{
		long long sum=0;
		for(int i=0; i<s.length(); i++)
		{
			if(s[i]>='A'&&s[i]<='F')
			   sum=sum*16+s[i]-'A'+10;
			else
			   sum=sum*16+s[i]-'0';
		}
		cout<<sum<<endl;
	}
	return 0;
 } 

这两种转化是基础,其余都是在此上变化组合

如八进制转化为十六进制,就是将值先转化为十进制,再转为十六进制,两者结合即可

更多推荐

蓝桥杯练习(进制转换)