数制转换需要逆序输出,就需要用到栈。所以我们直接用递归调用了。
#include<iostream>
#include<cstdio>
using namespace std;
void ttor(int n,int r)
{
if(n)
{
ttor(n/r,r);
printf("%c",n%r>9?n%r-10+'A':n%r+'0');
}
}
int main()
{
int n,r;
while(cin>>n>>r)
{
if(n>0)
ttor(n,r);
else if(n==0)
putchar('0');
else
{
putchar('-');
ttor(-n,r);
}
putchar('
');
}
}
值得注意的是:需要判断n==0? 不然十进制0转换r进制结果会是000..00