[C语言]模拟实现C语言库函数atof

来源:互联网 发布:通达oa即时通讯端口 编辑:程序博客网 时间:2024/05/29 04:30

题目:模拟实现C语言库函数atof

思路:

1.要记录小数点后面的位数,遇到小数点后,将count++,count不为零后,开始计算个数。

2.处理各种情况如 空格,正负号,异常。


//编写一个函数,实现功能类似于atof,例如将“12.34”变成数字12.34#include<stdio.h>#include<stdlib.h>#include<assert.h>#include <ctype.h>  //isspace头文件double my_atof(char* p){//要记录小数点后的位数,方便最后计算浮点数。int count = 0;int flags = 1;double a = 0.0;double ret = 0.0;assert(p);while (isspace(*p))  //判断空格{p++;}while (*p) {if (count)//count初值0,遇到.后count++就开始计算小数点后的位数count *= 10;if (*p == '+')p++;else if (*p == '-'){flags = -1;p++;}else if (*p == '.'){count++;p++;}else if (*p >= '0'&&*p <= '9'){ret = (ret * 10 + *p - '0');p++;}elsereturn 0;}return ret / count;}int main(){printf("%f\n", my_atof(" +23.45"));printf("%f\n", my_atof(" -2.345"));printf("%f\n", my_atof("+234.5"));printf("%f\n", my_atof("-23.45"));printf("%f\n", my_atof("2.345"));printf("%f\n", my_atof("234.5"));printf("%f\n", my_atof(" ."));printf("%f\n", my_atof("12.3ab"));system("pause");return 0;}


1 0
原创粉丝点击