#include <iostream>
using namespace std;
const char NULL_TERMINATED = '\0';
const char POINT = '.';
const int ONE = 1;
//const int ZERO = 0;
const int TEN = 10;
const int CHAR_MORE_THAN_INT = '0' - 0;
const double ZERO_DOUBLE = 0.0;
const double ONE_DOUBLE = 1.0;
const double POINT_ONE = 0.1;
//2009.07.21 22:36
double my_atof( char *str )
{
if (NULL == str)
{
throw;
}
else
{
char *const address = str;
while ( POINT != *(str + ONE) && NULL_TERMINATED != *(str + ONE))
{
++str;
}
char *const pointPrev = str;
double temp = ONE_DOUBLE;
double count = ZERO_DOUBLE;
while ((address - ONE) != str)
{
count += (double)(*str - CHAR_MORE_THAN_INT) * temp;
temp *= TEN;
--str;
}
///再转换小数部分
if (NULL_TERMINATED != *(pointPrev + ONE + ONE))
{
str = pointPrev + ONE + ONE;
double tempPoint = POINT_ONE;
while (NULL_TERMINATED != *str)
{
count += (double)(*str - CHAR_MORE_THAN_INT) * tempPoint;
tempPoint *= POINT_ONE;
++str;
}
}
return count;
}
}
int main( void )
{
char str[] = "1.23456789";
cout << my_atof( str ) << endl;
double val = 1.23456789;
cout << val << endl;
system( "PAUSE" );
return EXIT_SUCCESS;
}
/*=============
1.23457
1.23457
请按任意键继续. . .
===================*/
实现atof()函数原型:数字串转换成双精度浮点double
最新推荐文章于 2022-09-08 08:30:43 发布