|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>#include <math.h>char* myitoa ( int num , char *str ) ;int main ( ){ char str[ 10 ] ; printf ( "%s\n" , myitoa ( 638 , str ) ) ; printf ( "%s\n" , myitoa ( -1234 , str ) ) ; return 0 ;} char* myitoa ( int num , char *str ){ int ascii[ 10 ] = { 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 } ; int bit = 0 , i ; double temp , b ; temp = fabs ( ( double )num ) ; while ( temp > 1 ) { bit ++ ; temp /= 10.0 ; } int a[ bit ] ; for ( i = 0 ; i < bit ; i ++ ) { a[ i ] = 0 ; } for ( i = 0 ; i < bit ; i ++ ) { temp *= 10.0 ; printf ( "%lf " , temp ) ; a[ i ] = ( int )temp ; printf ( "%d " , a[ i ] ) ; temp -= a[ i ] ; } if ( num > 0 ) { for ( i = 0 ; i < bit ; i ++ ) { str[ i ] = ascii[ a[ i ] ] ; } str[ bit ] = '\0' ; } else if ( num < 0 ) { str[ 0 ] = '-' ; for ( i = 0 ; i < bit ; i ++ ) { str[ i + 1 ] = ascii[ a[ i ] ] ; } str[ bit + 1 ] = '\0' ; } return str ;}这是我的代码,然后运行之后,为什么好好的8.0还有4.0强制转化之后就变成其他的数字了
你的代码应该是:
- #include <stdio.h>
- #include <math.h>
- char* myitoa ( int num , char *str ) ;
- int main ( )
- {
- char str[ 10 ] ;
- printf ( "%s\n" , myitoa ( 638 , str ) ) ;
- printf ( "%s\n" , myitoa ( -1234 , str ) ) ;
- return 0 ;
- }
- char* myitoa ( int num , char *str )
- {
- int ascii[ 10 ] = { 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 } ;
- int bit = 0 , i ;
- double temp , b ;
- temp = fabs ( ( double )num ) ;
-
- while ( temp > 1 )
- {
- bit ++ ;
- temp /= 10.0 ;
- }
- int a[ bit ] ;
-
- for ( i = 0 ; i < bit ; i ++ )
- {
- a[ i ] = 0 ;
- }
-
- for ( i = 0 ; i < bit ; i ++ )
- {
- temp *= 10.0 ;
- printf ( "%lf " , temp ) ;
- a[ i ] = ( int )temp ;
- printf ( "%d " , a[ i ] ) ;
- temp -= a[ i ] ;
- }
-
- if ( num > 0 )
- {
- for ( i = 0 ; i < bit ; i ++ )
- {
- str[ i ] = ascii[ a[ i ] ] ;
- }
- str[ bit ] = '\0' ;
- }
- else if ( num < 0 )
- {
- str[ 0 ] = '-' ;
- for ( i = 0 ; i < bit ; i ++ )
- {
- str[ i + 1 ] = ascii[ a[ i ] ] ;
- }
- str[ bit + 1 ] = '\0' ;
- }
- return str ;
- }
复制代码
看代码没看出什么毛病,只是类型转换偏麻烦而已。
但是,之后我调试的时候发现了异常!见下图:
temp /= 10.0; 这句,会导致结果精度出现偏差,具体原因,大概是计算机实际上是用减法在模拟除法的原因吧……
|
-
|