思路:
这是在模拟进制转换的短除法,取余然后除,值得注意的是我们这里目标数字可能是负数所以相应的余数可能就是负数,解决办法就是将余数-基数然后目标数+1,同样采用先进后出的stack来存储,方便后期输出
还有一点就是不要忘记当基数>10之后我们需要用16进制的表示方法。
#include <iostream>
#include <stack>
using namespace std;
int main()
{
int n,t;
stack <int>s;
cin>>n>>t;
cout<<n<<"=";
/*do while 应对输入n值为0的情况*/
do
{
int r=n%t;
n/=t;
if(r<0)
{
n+=1;
r-=t;
}
s.push(r);
}
while(n);
while(!s.empty())
{
int temp=s.top();
s.pop();
if(temp<=9&&temp>=0)
{
cout<<temp;
}
else
cout<<(char)('A'+temp-10);
}
cout<<"(base"<<t<<")"<<endl;
return 0;
}