c语言实现十进制与二、八、十六进制互转
# include <stdio.h>
# include <string.h>
# include <math.h>
void Ten1change ( int a, int B)
{
int n;
if ( a)
{
Ten1change ( a/ B, B) ;
n= a% B;
if ( n< 10 )
{
printf ( "%d" , n) ;
} else
{
printf ( "%c" , n+ 55 ) ;
}
}
else
{
printf ( "0" ) ;
}
}
void Ten2change ( double a, int B)
{
int cnt= 0 ;
while ( a!= 0 && cnt< 10 )
{
double num= a* B;
int num1= ( int ) num;
if ( num1< 10 )
{
if ( cnt== 0 )
printf ( ".%d" , num1) ;
else
printf ( "%d" , num1) ;
}
else
{
if ( cnt== 0 )
printf ( ".%c" , num1+ 55 ) ;
else
printf ( "%c" , num1+ 55 ) ;
}
a= num- num1;
cnt++ ;
}
}
void Tenjudge ( char str[ 10 ] , int B)
{
int a= 0 ;
double b= 0 ;
if ( NULL == strchr ( str, '.' ) )
{
sscanf ( str, "%d" , & a) ;
Ten1change ( a, B) ;
} else
{
sscanf ( str, "%lf" , & b) ;
int num1= ( int ) b;
double num2= b- num1;
Ten1change ( num1, B) ;
Ten2change ( num2, B) ;
}
}
void Toten ( char str[ ] , int B)
{
char * s = "." ;
char * token;
token = strtok ( str, s) ;
int len= strlen ( token) ;
double num= 0 ;
double sum= 0 ;
for ( int i= 0 ; i< len; i++ )
{
if ( token[ i] >= '0' && token[ i] <= '9' )
{
num= token[ i] - '0' ;
}
else if ( token[ i] >= 'A' && token[ i] <= 'F' )
{
num= token[ i] - 'A' + 10 ;
}
sum+= num* pow ( B, len- 1 - i) ;
}
token = strtok ( NULL , s) ;
len= strlen ( token) ;
for ( int j= 0 ; j< len; j++ )
{
if ( token[ j] >= '0' && token[ j] <= '9' )
{
num= token[ j] - '0' ;
}
else if ( token[ j] >= 'A' && token[ j] <= 'F' )
{
num= token[ j] - 'A' + 10 ;
}
sum+= num* pow ( B, - ( j+ 1 ) ) ;
}
printf ( "%lf" , sum) ;
}
void main ( )
{
int flag= 1 ;
int k;
int B;
char str[ 20 ] = "" ;
while ( flag)
{
printf ( "**********************************\n" ) ;
printf ( "请选择所需进行的进制转换\n" ) ;
printf ( "1.十进制转(二、八、十六)进制\n" ) ;
printf ( "2.(二、八、十六)进制转十进制\n" ) ;
printf ( "**********************************\n" ) ;
printf ( "请选择数字:" ) ;
scanf ( "%d" , & k) ;
if ( k== 1 )
{
printf ( "请输入待转换的十进制数:" ) ;
scanf ( "%s" , str) ;
printf ( "请输入需要转换成几进制:" ) ;
scanf ( "%d" , & B) ;
Tenjudge ( str, B) ;
printf ( "\n" ) ;
} else if ( k== 2 )
{
printf ( "请输入待转换的(2,8,16)进制:" ) ;
scanf ( "%d" , & B) ;
printf ( "请输入待转换的(2,8,16)进制数:" ) ;
scanf ( "%s" , str) ;
Toten ( str, B) ;
printf ( "\n" ) ;
}
printf ( "继续请输入1,否则输入0:\n" ) ;
scanf ( "%d" , & flag) ;
}
}