当扫描字符数组不需要地址"str“而不是"&str”时,字符数组会衰减到指针。现在主要的问题是你为什么会有麻烦。记住,所有整数也是双/浮点数。也就是说,整数是浮点数的完美子集。因此,如果首先检查整型/读入int变量,则始终匹配任何浮点数,因为用户输入的浮点数在读取时将被截断为int,因此永远不会执行分支检查。

修复它的方法是首先测试浮点number.So读取输入到double,然后如果是真的,则通过将它转换为整数来测试它是否为整数,并查看相对差异以查看它是否小于某种公差。

因此,修复此问题的代码如下所示

代码语言:javascript复制#include "stdio.h"

#include "stdlib.h"

#include "math.h"

int main()

{

char input[100] = "";

double x;

int num;

char str[20] = "";

int assignment[5] = {0};

double tolerance = 1e-12;

printf("Pls. provide input: ");

fgets(input, 100, stdin);

if (sscanf(input, "%lf", &x) == 1) {

// Is it a number? All integers are also doubles.

num = (int)x; // We cast to int.

if ( fabs(x - num)/x > tolerance ) {

printf("The input is a floating point\n");

} else {

printf("The input is a integer\n");

}

} else if (sscanf(input, "%s", str) == 1) {

// Check if it is string

printf("The input is a string\n");

} else {

// No match error.

printf("input not recognized\n");

}

}样本

gcc试验

请给我。提供投入:3

输入是一个整数。

请给我。提供投入: 3.3

输入是浮点。

注意,,您应该使用更有意义的东西,比如机器精度,而不是我展示的容忍。