進制轉換,題目要求實現2-16之間任意進制的相互轉換,超過10的數字用A、B、C等表示,結果不能超過7位,否則輸出ERROR。思路是先將原數字轉換為十進制,然后再轉換為目標進制。字符串處理問題,注意細節。
表揚一下秀,又讓我學到了不少東西。
代碼如下:


#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
小鼠標 閱讀(190)
評論(0) 編輯 收藏 引用 所屬分類:
水題