编写一个函数,将一个数字字符串转换成这个字符串对应的数字(包括正浮点数、负浮点数)

来源:互联网 发布:轮播图原生js代码 编辑:程序博客网 时间:2024/05/29 13:24
/**************************************** *  File Name  : comprehensive.c *  Creat Data : 2015.3.9*  Author     : ZY *****************************************/ #include <stdio.h>#include <math.h>/*编写一个函数,将一个数字字符串转换成这个字符串对应的数字(包括正浮点数、负浮点数)例如:“12.34“  返回12.34 “-123.34“ 返回-123.34函数原型:double my_atof(char *str){}*/double my_atof(char *str){double num = 0.0;double result = 0.0;int i,j,k;if(str[0] == '-'){printf("-");for(i = 1; str[i] != '\0'&&str[i] != '.';i++){num = str[i] + (0 - '0');result = result * 10 + num;  }i++;for(j = i,k = 1;str[j] != '\0';j++,k++){num = str[j] +  (0 - '0');result = result + num * pow(0.1,k);}}else{for(i = 0; str[i] != '\0'&&str[i] != '.';i++){num = str[i] + (0 - '0');result = result * 10 + num;  }i++;for(j = i,k = 1;str[j] != '\0';j++,k++){num = str[j] +  (0 - '0');result = result + num * pow(0.1,k);}}return result;}int main(void){char *str1 = "12.34";char *str2 = "-123.34";printf("%f\n",my_atof(str1));printf("%f\n",my_atof(str2));return 0;}





#include <stdio.h>#include <ctype.h>double my_atof(char *str){int flag = 1;int count = 1;double num = 0;double value = 0;while(isspace(*str)){*str++;}if(*str == '-'){flag = -1;*str++;}if(*str == '+'){*str++;}while(*str != '\0'&&*str != '.'){value = value * 10 + (*str - '0');*str++;}*str++;while(*str != '\0'){count *= 10;num = num * 10 + (*str - '0');*str++;}num = num/count;return  flag * (value + num);}int main(void){char *str1 = "12.34";char *str2 = "-123.34";printf("%f\n",my_atof(str1));printf("%f\n",my_atof(str2));return 0;}




#include <stdio.h>#include <math.h>#include <ctype.h>double my_atof(char *str){int flag = 1;double value = 0;double num = 0;int count = 0;//判断空白字符while(isspace(*str)){str++;}//判断正负号if(*str == '-'){flag = -1;str++;}if(*str == '+'){str++;}//isdigtilwhile(*str != '\0'){if(*str == '.'){count++;str++;continue;}if(count){count *=10;}value = value * 10 + (*str -'0');str++;}value = value / count;return flag * (value);}



0 0
原创粉丝点击