题目一:输出对应的数据类型 程序如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 #include <stdio.h> #include <string.h> #include <ctype.h> int main (void ) { char input[100 ]; fgets(input, sizeof (input), stdin ); input[strcspn (input, "\n" )] = 0 ; if (strlen (input) == 1 && isprint (input[0 ])) printf ("Data type: char, ASCII value: %d\n" , (int )input[0 ]); else { char *endptr; long intValue = strtol(input, &endptr, 10 ); if (endptr != input && *endptr == '\0' ) printf ("Data type: int\n" ); else { float floatValue = strtof(input, &endptr); if (endptr != input && *endptr == '\0' ) printf ("Data type: float\n" ); else { double doubleValue = strtod(input, &endptr); if (endptr != input && *endptr == '\0' ) printf ("Data type: double\n" ); else printf ("Error\n" ); } } } }
由于C语言把char类型视为特殊的int来处理,所以上述代码只能区分int,char和float。 对于数字的char类型(例如字符‘1’),以及double和float并不能很好地区分开来(目前也是没有想到什么好办法)