字符串转浮点数

今天看到一个题,让把字符串转成浮点数,列了一下,需要注意的应该就是这几点

  • 前导空白字符
  • 符号位
  • 前导零
#include <stdio.h>
#include <string.h>
#include <math.h>

double a2f(char *str) {
	// leading space
	while (*str==' ' || *str=='t') {
		str++;
	}

	// judge sign
	int sign = 1;
	if (*str == '-') {
		sign = -1;
		str++;
	} else if (*str=='+') {
		sign = 1;
		str++;
	} else if (*str>='0' && *str<='9') {
		sign = 1;
	} else {
		// exception
		return 0;
	}

	// leading zero
	while (*str == '0') {
		str++;
	}

	int integer=0, decimals=0, e=0;
	int point_found = 0;
	for (; *str!='\0'; str++) {
		if (*str>='0' && *str<='9') {
			if ( ! point_found) {
				integer = integer*10 + (*str-'0');
			} else {
				decimals = decimals*10 + (*str-'0');
				e++;
			}
		} else if (*str == '.') {
			if ( ! point_found) {
				point_found = 1;
			} else {
				// exception
				return 0;
			}
		} else {
			// exception
			return 0;
		}
	}

	return sign*(integer+decimals*pow(10, e*-1.0));
}

int main() {
	printf("%lfn", a2f("-000123.45600"));
	return 0;
}

==================================

2012-10-14 19:18:25 update 哦,对了,上面的代码没有考虑浮点溢出

Leave a Reply

Your email address will not be published. Required fields are marked *