使用c语言编写一个函数,将一个数字字符串转化为对应数字,不考虑溢出,(比如“12.34”转换为数字:12.34),考虑异常输入
思考:异常如输入字幕等等,也有可能输入‘+’,‘-’号等,
程序如下:
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
double my_atof(const char* str)
{
assert(str);
double num = 0;
int flag = 0;
int point = 0;
while (*str)
{
int value = 1;
if ('-' == *str && 0 == flag)
flag = -1;
else if ('-' == *str && 1 == flag)
flag = -1;
else if ('-' == *str && -1 == flag)
flag = 1;
else if ('+' == *str && 0 == flag)
flag = 1;
if (*str == '.'&&point == 0)
point++;
int temp = point;
if ((*str >= '0') && (*str <= '9') && (0 == point))
num = 10 * num + *str - '0';
else if ((*str >= '0') && (*str <= '9') && (point > 0))
{
temp--;
while (temp--)
value = value * 10;
num = num + (double)(*str - '0') / value;
}
str++;
if (point > 0)
point++;
}
if (-1 == flag)
num = -num;
return num;
}
int main()
{
double n, m;
char buffer[256];
printf("Enter degrees: ");
fgets(buffer, 256, stdin);
n = my_atof(buffer);
printf("The number is: %f \n", n);
system("pause");
return 0;
}
如有错误与考虑不周 敬请指正!!
本文出自 “分享中进步” 博客,请务必保留此出处http://xmwen1.blog.51cto.com/10730069/1741609