将一个字符串转换为浮点数

来源:互联网 发布:dell无限网络驱动 编辑:程序博客网 时间:2024/05/08 18:13
#include <stdio.h>#include <stdlib.h>#include <math.h>double atof(const char *s){int i = 0;int k = 0;double j;int flag = 1;double result = 0.0;while (s[i] == ' '){i++;}if (s[i] == '+'){i++;}if (s[i] == '-'){i++;flag = -1;}while (s[i] != '\0' && s[i] != '.'){if (s[i] < '0' || s[i] > '9'){printf("字串含有非数字字符,无法转换!\n");exit(0);}j = (s[i] - '0')*1.0;result = result*10+j;i++;}if (s[i] == '.'){i++;while (s[i] != '\0'){if (s[i] < '0' || s[i] > '9'){printf("字串含有非数字字符,无法转换!\n");exit(0);}k++;j = s[i] - '0';result = result+(1.0 * j)/pow(10,k);i++;}}result = flag * result;return result;}int main(){double i;char str[100];printf("请输入一个字符串:");gets(str);i = atof(str);printf("您输入的字符串转换为浮点数是:%f\n",i);return 0;}

原创粉丝点击