首页 > 代码库 > atof函数扩充

atof函数扩充

k&r习题4-2,扩充使可以处理科学计数法形式
#include<ctype.h>

double atof(char s[])
{
	double val, power, e_sum;
	int e_val;
	int i, sign, e_sign;

	for (i = 0; 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_sign = (s[i] == ‘-‘) ? (-1) : 1;
	e_sum = 1.0;
	if (s[i] == ‘+‘ || s[i] == ‘-‘)
		i++;
	for (e_val = 0; isdigit(s[i]); i++)
		e_val = 10 * e_val + (s[i] - ‘0‘);
	for (i = 0; i < e_val; i++) {
		if (e_sign > 0)
			e_sum *= 10;
		else
			e_sum /= 10;
	}

	return sign * val / power * e_sum;
}



这是自己写的那个,思路比较简单,基本就是前面步骤的复制,只不过判断的内容换了,这样就显得又臭又长。
答案上那个简洁些,没增加新的变量,用了前面的。

atof函数扩充