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

#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
请按任意键继续. . .
===================*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值