進制轉換

將n 進制數x,轉換爲m 進制數y輸出.(n,m<=20)ios

 

輸入格式spa

x<n>mcode

 

輸出格式blog

x<n>=y<m>string

 

樣例輸入it

48<10>8io

 

樣例輸出class

48<10>=60<8>stream

 

沒啥好講的,先轉化成10進制,再轉化成其餘進制。di

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cmath>
 4 #include<algorithm>
 5 #include<cstring>
 6 using namespace std;
 7 #define rep(i, a, n) for(int i = a; i <= n; ++i)
 8 #define per(i, n, a) for(int i = n; i >= a; --i)
 9 typedef long long ll;
10 const int maxn = 1e2 + 5;
11 char ax[20] ={'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
12 char a[maxn], num[maxn], nnum[maxn];
13 ll pre, now, chanum;
14 void retu()        //先轉換成10進制 
15 {
16   ll x = 1;
17   per(i, strlen(num) - 1, 0)
18     {
19       int y = num[i] >= 'A' ? num[i] - 'A' + 10 : num[i] - '0';
20       chanum += y * x;
21       x *= pre;
22     }
23 }
24 void change(ll num)        //在轉換成n進制 
25 {
26   int pos = 0;
27   while(num > 0)
28     {
29       int x = num % now;
30       nnum[++pos] = x > 9 ? ax[x - 10] : x + '0';
31       num /= now;
32     }
33 }
34 int main()
35 {
36   scanf("%s", a);
37   int i = 0;
38   while(a[i] != '<') {num[i] = a[i]; i++;}
39   ++i;
40   while(a[i] != '>') {pre = pre * 10 + a[i] - '0'; i++;}
41   ++i;
42   while(i < strlen(a)) {now = now * 10 + a[i] - '0'; i++;}
43   retu();
44   change(chanum);
45   printf("%s<%lld>=", num, pre);
46   per(i, strlen(nnum + 1), 1) printf("%c", nnum[i]);
47   printf("<%lld>\n", now);
48   return 0;
49 }
相關文章
相關標籤/搜索