exc/k&r/04-funcs-and-prog-struct/04-02.c

60 lines
1.1 KiB
C

#include <stdio.h>
#include <ctype.h>
#include <math.h>
#define DEC_SEP X('.') X(',')
#define EXP_SEP X('e') X('E')
double atof(char *s);
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("error: expected argument\n");
return 1;
}
printf("%f\n", atof(argv[1]));
return 0;
}
/* macros for atof */
#define SIGN(s) \
((*s == '-') ? (s++, -1) : ((*s == '+') ? (s++, 1) : 1))
#define ATOI(s, x, ...) \
for (; isdigit(*s); s++, ##__VA_ARGS__) \
x = 10 * x + (*s - '0')
/* atof: convert string s to double */
double atof(char s[])
{
double val;
while (isspace(*s))
s++;
/* integer part */
int sign = SIGN(s);
ATOI(s, val);
#define X(sep) *s != sep &&
if (DEC_SEP 1) return sign * val;
#undef X
s++;
/* fractional part */
int exp = 0;
ATOI(s, val, exp--);
val *= sign * pow(10, exp);
#define X(sep) *s != sep &&
if (EXP_SEP 1) return val;
#undef X
s++;
/* exponent */
sign = SIGN(s);
exp = 0;
ATOI(s, exp);
return val * pow(10, sign * exp);
}