多数编程语言中的输出语句以10进制(基为10)作为默认格式显示整型数据。对于有些应用,特别是系统程序,,可能想用2进制(基为2),8进制(基为8)或(16)进制输出。
这时候可以编程实现10进制到n进制的转换。
可以采用除数取余法。出发过程得到的余数为最终的输出,但应按相反的顺序。比如余数是2,1,3,这正确输出应该是312;使用栈的LIFO(先进后出)的特性,我们把余数一个个入栈,待除数为0时,把数字一个一个出栈,直到栈为空,这样就是按照正确的顺序了
用到栈的STL有push()入栈,pop()出栈,top()取栈顶元素;
#include<iostream>
#include<stack>
#include<cstring>
using namespace std;
stack<char> s;
int main()
{
int n,temp,b; //n为十进制 b为要转换的进制
string digitchar="0123456789ABCDEF";
while(cin>>n>>b)
{
while(n) //如果n不为0,则继续除数取余
{
temp=n%b;
s.push(digitchar[temp]); //将余数压入栈
n/=b;
}
while(!s.empty()) //出栈
{
cout<<s.top();
s.pop();
}
cout<<endl;
}
return 0;
}