#include "stdio.h"
#include "math.h"
main()
{
int error,i,j,k,number_b,number_d,temp;
char type;
char number_copy[60],number[60];
error=1;
number_d=0;
printf("please choose type,1--Binery,2--Decimal,3--Hex\n");
scanf("%c",&type);
while((type!='1')&&(type!='2')&&(type!='3'))
{
printf("type error,please input the type again\n");
scanf("%c",&type);
}
switch (type)
{
case '1':
{
printf("\nplease input the binery number:");
scanf("%s",number);
/*判断二进制输入是否合法,不合法重新输入*/
while (error==1)
{
for(i=0;number[i]!='\0';i++)
{
if((number[i]!='0')&&(number[i]!='1'))
{
error=1;
break;
}
else
error=0;
}
if(error==0)
break;
else
{
printf("\nnumber error,pls input again:\n");
scanf("%s",number);
}
}
/*输入的二进制转换为十进制和十六进制输出*/
for(i=i-1,j=0;i>=0;i--,j++)
{
number_d=(number[j]-48)*pow(2,i)+number_d;
}
printf("\nthe decimal number is:%d\nthe hex number is:%X",number_d,number_d);
}
break;
case '2':
{
printf("\nplease input the decimal number:");
scanf("%s",number);
/*判断二进制输入是否合法,不合法重新输入*/
while(error==1)
{
for(i=0;number[i]!='\0';i++)
{
if(number[i]<'0'||number[i]>'9')
{
error=1;
break;
}
else
error=0;
}
if(error==0)
break;
else
{
printf("\nnumber error,pls input again:\n");
scanf("%s",number);
}
}
/*输入的十进制转换为二进制和十六进制输出*/
for(i=i-1,j=0;i>=0;i--,j++)
{
number_d=(number[j]-48)*pow(10,i)+number_d;
}
printf("\nthe hex number is:%X",number_d);
for(i=0;number_d!=0;i++)
{
number[i]=number_d%2+48;
number_d=number_d/2;
}
for(j=i-1,k=0;k<(i-1)/2+1;j--,k++)
{
temp=number[j];
number[j]=number[k];
number[k]=temp;
}
printf("\nthe binary number is:%s",number);
}
break;
case '3':
{
printf("\nplease input the hex number:");
scanf("%s",number);
/*判断十六进制输入是否合法,不合法重新输入*/
while(error==1)
{
for(i=0;number[i]!='\0';i++)
{
if((number[i]>='0'&&number[i]<='9')||(number[i]>='a'&&number[i]<='f')||(number[i]>='A'&&number[i]<='F'))
{
error=0;
}
else
{
error=1;
break;
}
}
if(error==0)
break;
else
{
printf("\nnumber error,pls input again:\n");
scanf("%s",number);
}
}
/*输入的十六进制转换为二进制和十进制输出*/
for(i=i-1,j=0;i>=0;i--,j++)
{
if(number[j]>='0'&&number[j]<='9')
number_d=(number[j]-48)*pow(16,i)+number_d;
else if(number[j]>='a'&&number[j]<='f')
number_d=(number[j]-87)*pow(16,i)+number_d;
else if(number[j]>='A'&&number[j]<='F')
number_d=(number[j]-55)*pow(16,i)+number_d;
}
printf("\nthe decimal number is:%d",number_d);
for(i=0;number_d!=0;i++)
{
number[i]=number_d%2+48;
number_d=number_d/2;
}
for(j=i-1,k=0;k<(i-1)/2+1;j--,k++)
{
temp=number[j];
number[j]=number[k];
number[k]=temp;
}
printf("\nthe binary number is:%s",number);
}
break;
}
}
我这个有错误输入提示,且输入范围错误后会弹出重新输入,测试正确