您的位置:首页 > 其它

实现atof()函数原型:数字串转换成双精度浮点double

2012-05-10 08:37 267 查看
#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
请按任意键继续. . .
===================*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐