不知道符不符合你的要求。
程序代码:
#include <stdio.h>
#include <ctype.h>
#define MAXLINE 100
double atof(char s[]);
int getline(char s[],int max);
int main(void)
{
char line[MAXLINE];
while(getline(line,MAXLINE) > 0)
printf("%lf\n",atof(line));
printf("Bye!\n");
return 0;
}
int getline(char s[], int max)
{
int i, c;
for(i = 0; i < max - 1 && (c = getchar()) != EOF && c != '\n'; i++)
s[i] = c;
if(c == '\n')
s[i++] = c;
s[i] = '\0';
return i;
}
double atof(char s[])
{
double val, power,powers;
int i,sign,signs,exp;
for(i = 0; isspace(s[i]); i++)//跳过空白字符
;
sign = (s[i] == '-')?-1:1;//判断正负
if(s[i] == '+' || s[i] == '-')//跳过正负符号
i++;
for(val = 0.0; isdigit(s[i]); i++)//计算小数点前的数值
val = 10.0 * val + (s[i] - '0');
if(s[i] == '.')
i++;
for(power = 1.0; isdigit(s[i]); i++)//计算小数点后的数字
{
val = 10.0 * val + (s[i] - '0');
power *= 10.0;
}
//判断字符串是不是科学计数法,是则计算,否则返回
if(s[i] == 'E' || s[i] == 'e')
{
i++;//跳过字符E或e
signs = (s[i] == '-')?-1:1;//判断指数的正负
if(s[i] == '-' || s[i] == '+')//跳过指数的正负符号
i++;
if(isdigit(s[i]))
{
for(exp = 0;isdigit(s[i]); i++)
exp = 10 * exp + (s[i] - '0');
for(powers = 1.0; exp > 0; exp--)
powers *= 10.0;
}
}
else
return sign * val / power;
if(signs == -1)
return sign * (val / power / powers);
else
return sign * (val / power * powers);
}
[此贴子已经被作者于2017-2-16 14:05编辑过]