条件问题时做

do while conditions issue

所以我试图确保用户在一组特定条件下输入一个变量,以便在以后的计算中使用。即不能超过vmax,不能小于零,不能是字符串。

这就是我得到的。

    do
    {
        scanf("%f", &vkmh);
        if (vkmh <= vmax)
        {
        }           
        else if (vkmh < 0)
        {
            printf("Error, speed must be positive.\n");
        }
        else if (vkmh > vmax)
        {
            printf("Error, the max speed of this vehicle is listed as %.fkm/h.\nIt cannot exceed that value. Please enter a value under %.f.\n", vmax, vmax);
        }
        else if (vkm != getchar())
        {
            printf("Error in input. Please only use numbers\n");
        }
    }
    while(vkmh > vmax || vkmh < 0 || vkm != getchar());

理论上有效值 return 有效响应,高于 vmax 的值 return 无效响应并请求用户重新输入。但是负数或字符串不会 return 任何东西。

关于如何让它工作的任何想法?

首先这是 C,不是 C#。 getchar 从标准输入读取,因此在每次迭代中调用(最多)3 次 getchar() 并读取 3 次用户输入。所以你可以删除这些电话。

scanf 函数 return 成功转换的次数,因此您可以使用此 (==1) 检查用户是否输入了正确的浮点值。

编辑:我删除了代码,因为我无法在 phone 上编译,抱歉 像本页示例中那样使用 fgets / atof http://www.cplusplus.com/reference/cstdlib/atof/

您可以使用下面的代码来实现您要查找的内容。请注意,答案与此答案非常相似:

How to scanf only integer and repeat reading if the user enter non numeric characters?

#include<stdlib.h>
#include<stdio.h>

int clean_stdin()
{
    while (getchar()!='\n');
    return 1;
}

int main ()
{
    float vkmh, vmax = 100.0;

    setbuf(stdout, NULL);

    vkmh = vmax + 1.0; /* value to start the loop */
    while ( vkmh < 0 || vkmh > vmax) {
        printf("Please enter value for the velocity in km/h: ");
        if (scanf("%f",&vkmh) == 1) {
            if (vkmh < 0) {
                /* This was your 2nd if condition, but would never have executed assuming that vmax > 0. */
                printf("Error, speed must be positive.\n");
                exit(1);
            } else if (vkmh <= vmax) {
                /* Do something */
            } else {
                /* No need for the else if, this is the only other possibility */
                printf("Error, the max speed of this vehicle is listed as %.fkm/h.\n"
                       "It cannot exceed that value. Please enter a value under %.f.\n", vmax, vmax);
            }
        } else {
            printf("Error in input.\n");
            clean_stdin();
        }
    }
    printf("\nValue read: %f km/h\n",vkmh);
    return 0;
}