進(jìn)制轉(zhuǎn)換,題目要求實(shí)現(xiàn)2-16之間任意進(jìn)制的相互轉(zhuǎn)換,超過10的數(shù)字用A、B、C等表示,結(jié)果不能超過7位,否則輸出ERROR。思路是先將原數(shù)字轉(zhuǎn)換為十進(jìn)制,然后再轉(zhuǎn)換為目標(biāo)進(jìn)制。字符串處理問題,注意細(xì)節(jié)。
表揚(yáng)一下秀,又讓我學(xué)到了不少東西。
代碼如下:


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define LEN 200
int main()
{
int i, j;
char str0[LEN];
char str1[LEN];
char str2[LEN];
int a, b;
while(gets(str0))
{
sscanf(str0, "%s%d%d", str1, &a, &b);
int len = strlen(str1);
for(i = 0; i < len; i++)
{
if(isdigit(str1[i]))
str1[i] -= '0';
else
str1[i] = str1[i] - 'A' + 10;
}
int sum = 0;
for(i = 0; i < len; i++)
{
sum *= a;
sum += str1[i];
}
int count = 0;
while(sum > 0)
{
str2[count++] = sum % b;
sum /= b;
}
if(count > 7)
printf(" ERROR");
else
{
for(i = 0; i < 7 - count; i++)
putchar(' ');
for(i = count - 1; i >= 0; i--)
printf("%c", str2[i] >= 10 ? str2[i] - 10 + 'A' : str2[i] + '0');
}
putchar(10);
}
//system("pause");
}
posted on 2012-08-10 16:58
小鼠標(biāo) 閱讀(182)
評論(0) 編輯 收藏 引用 所屬分類:
水題