在TC2.0环境下写将浮点数字字符串转换成浮点数的函数 atof( )。对空字符串 返回0.0;对含有非法字符的串给出提示并将非法字符之前的值进行转换
时间: 2023-07-15 07:10:50 浏览: 61
下面是一个简单的实现:
```c
double atof(const char *str) {
if (strlen(str) == 0) { // 空字符串
return 0.0;
}
const char *p = str;
int count_dot = 0;
int count_digit = 0;
bool negative = false;
if (*p == '-') { // 处理负号
negative = true;
p++;
}
double result = 0.0;
bool found_digit = false;
while (*p != '\0') {
if (*p == '.') { // 处理小数点
if (++count_dot > 1) { // 小数点个数超过1个
printf("Invalid input: too many dots\n");
return result;
}
} else if (*p >= '0' && *p <= '9') { // 处理数字
found_digit = true;
result = result * 10.0 + (*p - '0');
count_digit++;
} else { // 非法字符
printf("Invalid input: invalid character '%c'\n", *p);
if (found_digit) {
break;
} else {
return 0.0;
}
}
p++;
}
if (count_digit == 0) { // 没有数字
return 0.0;
}
if (count_dot > 0) { // 处理小数部分
result /= pow(10, count_digit - count_dot);
}
if (negative) { // 处理负数
result = -result;
}
return result;
}
```
这个函数首先处理特殊情况,如空字符串和只有负号的字符串。然后它遍历整个字符串,处理小数点和数字。如果发现非法字符,它会给出提示并返回已经转换的值。如果没有数字,它将返回0.0。最后,它将处理小数部分和负号,并返回转换后的浮点数。