c - 我如何防止我的代码接受小数,并且只接受整数

标签 c

所以我正在尝试检查用户是否输入了十进制值,代码会打印出无效值并要求输入另一个值。有任何想法吗? 对于 c 代码来说真的很新,任何指南或技巧都会受到欢迎。 我猜它与“值”*2 有关,如果该值是偶数,则为真,否则为假。 如果我是对的或错的请告诉我,问题是我不知道如何把它放在代码中

     do
        {
        printf("\nEnter value for 1st side of the Triangle: ");
        fflush(stdin);
        scanf("%d%*c", &side1);

        if((side1 <= 0) || (side1 > 999))
        {
            printf ("Invalid Value, Retry Input\n");
            fflush(stdin);
        }
        if ((side1 >= 1) && (side1 < 999))
        {
            printf("Enter value for 2nd side of the Triangle: ");
            fflush(stdin);
            scanf("%d%*c", &side2); 
        }   

        if ((side2 < 0) || (side2 > 999))
        {
            printf ("Invalid Value, Retry Input\n");
            fflush(stdin);
        }
        if ((side2 >= 1) && (side2 < 999))
        {
            printf("Enter value for 3rd side of the Triangle: ");
            fflush(stdin);
            scanf("%d%*c", &side3);
        }

        if ((side3 < 0) || (side3 > 999))
        {
            printf ("Invalid Value, Retry Input\n");
            fflush(stdin);
        }
        if ((side3 >= 1) && (side3 < 999))
        { 
            success = 1;
        }   
        }
        while(success == 0);

最佳答案

尝试读取字符串并使用 strtol 将其转换为整数。然后检查 **endptr 以查看它是否收到错误值( float )。

关于c - 我如何防止我的代码接受小数,并且只接受整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49426402/

相关文章:

c - 包含 Dev-C++ : Why isn't curses. h 吗?

c - 如何使用 gcc 显示预处理的宏(仅由用户定义)?

c - malloc() 和 calloc() 是否正确?

使用 ruby​​ FFI 在 ruby​​ 中创建静态数组类

CppUTest:如何将更多数据传递给特定的模拟调用?

c - ISO C90 禁止在 C 中混合声明和代码

c - 以 4 个单字节解析 ip 地址字符串

搜索整个二叉树后比较值

c - 如何在c中实现继承类?

C:将自由语句移动到单独的函数中会导致内存泄漏