相关知识:
头文件:#include <stdlib.h>
函数 atof() 用于将字符串转换为双精度浮点数(double),其原型为:
double atof (const char* str);
atof() 的名字来源于 ascii to floating point numbers 的缩写,它会扫描参数str字符串,跳过前面的空白字符(例如空格,tab缩进等,可以通过 isspace() 函数来检测),直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。参数str 字符串可包含正负号、小数点或E(e)来表示指数部分,如123. 456 或123e-2。
【返回值】返回转换后的浮点数;如果字符串 str 不能被转换为 double,那么返回 0.0。
程序如下:
#include <iostream>
using namespace std;
double myatof(const char* str)
{
double result = 0.0;
double d = 10.0;
int count = 0;
if(str == NULL)
return 0;
while(*str == ' ' || *str == '\t')
str++;
bool flag = false;
while(*str == '-') //记录数字正负
{
flag = true;
str++;
}
if(!(*str >= '0' && *str <= '9')) //非数字退出
return result;
while(*str >= '0' && *str <= '9') //计算小数点前面的部分
{
result = result*10 + (*str - '0');
str++;
}
if(*str == '.') //小数点
str++;
while(*str >= '0' && *str <= '9') //小数点后面的部分
{
result = result + (*str - '0')/d;
d*=10.0;
str++;
}
result = result * (flag ? -1.0 : 1.0);
if(*str == 'e' || *str == 'E') //科学计数法
{
flag = (*++str == '-') ? true : false;
if(*str == '+' || *str == '-')
str++;
while(*str >= '0' && *str <= '9')
{
count = count*10 + (*str - '0');
str++;
}
if(flag == true) //为-
{
while(count > 0)
{
result = result/10;
count--;
}
}
if(flag == false) //为+
{
while(count > 0)
{
result = result*10;
count--;
}
}
}
return result;
}
int main()
{
char *s1 = "123.456hfid";
char *s2 = "-12.45de";
char *s3 = "ds24.67";
char *s4 = "12.34e5ji";
char *s5 = "13.56e-2hu";
printf("result = %f\n",myatof(s1));
printf("result = %f\n",myatof(s2));
printf("result = %f\n",myatof(s3));
printf("result = %f\n",myatof(s4));
printf("result = %f\n",myatof(s5));
return 0;
}
运行结果如图所示: