typ eines strings bestimmen: int, long, float, double
-
hi,
ich moechte den type eines zu konvertierenden strings bestimmen...
warum gibt folgendes beispiel als integer erkannt?Reference: http://stackoverflow.com/questions/1997587/function-to-check-if-input-is-int-or-floating-pt-number
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <float.h> #include <limits.h> #include <errno.h> #include <math.h> #define F_EPS 1e-7 typedef enum datatype datatype; enum datatype { TYPE_INT, TYPE_LONG, TYPE_FLOAT, TYPE_DOUBLE, TYPE_INVALID }; const char *datatype_strings[] = { "TYPE_INT", "TYPE_LONG", "TYPE_FLOAT", "TYPE_DOUBLE", "TYPE_INVALID" }; datatype findtype(const char *s) { char *eptr; double d; double diff; errno = 0; d = strtod(s, &eptr); if ((d == 0 && eptr == s) || errno == ERANGE) return TYPE_INVALID; diff = d - floor(d+0.5); if (d <= INT_MAX && d >= INT_MIN && diff <= F_EPS) return TYPE_INT; if (d <= LONG_MAX && d >= LONG_MIN && diff <= F_EPS) return TYPE_LONG; if ((d > 0 && (d > FLT_MAX || d < FLT_MIN)) || (d < 0 && (d < -FLT_MAX || d > -FLT_MIN))) return TYPE_FLOAT; return TYPE_DOUBLE; } int main(void) { // your code goes here datatype type = findtype("1.5"); printf("type: %s\n", datatype_strings[type]); return 0; }
-
Mit einer weiteren Zeile hättest du das auch selbst herausfinden können:
if (d <= INT_MAX && d >= INT_MIN && diff <= F_EPS) { printf("%f|%f|%f\n",d,diff,F_EPS); return TYPE_INT; }
Gibt aus:
1.500000|-0.500000|0.000000 type: TYPE_INT
d ist 1.5, diff ist -0.5. und F_EPS ist 0. d ist größer als INT_MIN und kleiner ans INT_MAX, diff ist kleiner als F_EPS. Das ergibt einen wahren Ausdruck, und die Funktion sagt an, dass es sich um einen int handelt.
-
Meist gilt:
float
unddouble
unterscheiden sich nicht nur im Wertebereich.
Entscheidender ist die Anzahl der signifikanten Stellen.Mit
float
kannst du auch nicht jede Zahl darstellen, die mitlong
möglich ist.Ein
int
-Typ hast du, wenn du keine Nachkommstellen (bzw. kein Komma) hast.
Dies kannst du z.B. mitstrtol
feststellen, wenn eptr auf ein "." zeigt.