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

来源:互联网 发布:博思数据百度云 编辑:程序博客网 时间:2024/06/05 15:38
#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:36double 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.234571.23457请按任意键继续. . .===================*/

原创粉丝点击