UVA355
大致题意
就是进制转换(2-16进制)和对非法输入的处理
具体题目
Write a program to convert a whole number specified in any base (2..16) to a whole number in any
other base (2..16). “Digits” above 9 are represented by single capital letters; e.g. 10 by A, 15 by F, etc.
Input
Each input line will consist of three values. The first value will be a positive integer indicating the base of the number. The second value is a positive integer indicating the base we wish to convert to. The third value is the actual number (in the first base) that we wish to convert. This number will have letters representing any digits higher than 9 and may contain invalid “digits”. It will not exceed 10 characters. Each of the input values on a single line will be separated by at least one space.
Output
Program output consists of the original number followed by the string ‘base’, followed by the original base number, followed by the string ‘=’ followed by the converted number followed by the string ‘base’ followed by the new base. If the original number is invalid, output the statement original_Value is an illegal base original_Base number where original_Value is replaced by the value to be converted and original_Base is replaced by the original base value.
Sample input
2 10 10101
5 3 126
15 11 A4C
Sample output
10101 base 2 = 21 base 10
126 is an illegal base 5 number
A4C base 15 = 1821 base 11
#include <stdio.h>
#include <stdlib.h>
#include"string.h"
#include "ctype.h"
char base[15]= {'2','3','4','5','6','7','8','9','A','B','C','D','E','F','G'};
unsigned long long turndec(char str[],int B);
void changeObj(unsigned long long dec,int cB);
int main()
{
char a[50];
int B,cB,i,flag=1;
unsigned long long dec;
while(scanf("%d %d %s",&B,&cB,a)==3)
{
flag=1;//这一步初始化一定在这
for(i=0; a[i]!=0; i++)
{
if(a[i]>=base[B-2] || a[i]<'0')
{
printf("%s is an illegal base %d number\n",a,B);
flag=0;
break;
}
}
if(flag)
{
dec=turndec(a,B);
printf("%s base %d = ",a,B);
changeObj(dec,cB);
}
}
return 0;
}
unsigned long long turndec(char str[],int B)
{
unsigned long long len,num,sum=0;
int i;
unsigned long long pow=1;
len=strlen(str);
for(i=len-1; i>=0; i--)
{
if(isdigit(str[i]))
{
num=str[i]-'0';
}
else
num=str[i]-'A'+10;
sum=num*pow+sum;
pow*=B;
}
return sum;
}
void changeObj(unsigned long long dec,int cB)
{
char a[100]= {0};
int i=0,num,len;
if(dec==0)
a[0]='0';
while(dec/cB >=0 && dec!=0)
{
num=dec%cB;
if(num>=10)
{
a[i]='A'-10+num;
}
else
a[i]='0'+num;
dec=dec/cB;
i++;
}
len=strlen(a);
for(i=len-1; i>=0; i--)
{
printf("%c",a[i]);
}
printf(" base %d",cB);
printf("\n");
}
注意事项
1.最大输入10位 FFFFFFFFF,所以注意数组范围,和数据类型(long long)。
2.主函数中,flag变量在每一次 大while 要重新初始化,设为1。否则会造成在不经历if后,延续上一次的flag值,当flag=0时(但实际应该等于0),导致不做if(flag),没有输出,再次回到 大while。