把这题想复杂了,不过如果不好好梳理一下思路,这道题确实很难,
这一题主要是想到在不管转换成什么样进制都适用的公式.
while (n)
{
a[i] = n % r;
n = n / r;
i ++;
}
这就是解本题的关键!
当然肯定不是我想出来的,这就叫站在巨人的肩膀上,呼呼
还有一个很巧妙的地方,
就是当进制数大于十的话就要用字母"A,B,C"代替了,
本题就是用这么一个公式搞定的,
a[j] = a[j] - 10 + 'A';
很巧妙的说,有木有
下面的是代码:
#include <stdio.h>
#include <string>
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
int n, r, i, j;
int a[100];
while (cin >> n >> r)
{
i = 0;
if (n < 0)
{
n = -n;
printf ("-");
}
while (n)
{
a[i] = n % r;
n = n / r;
i ++;
}
for (j = i - 1; j >= 0; j --)
{
if (a[j] >= 0 && a[j] <= 9)
printf ("%d", a[j]);
else
{
a[j] = a[j] - 10 + 'A';
printf ("%c", a[j]);
}
}
printf ("\n");
}
system ("pause");
return 0;
}