所以我试图确定用户在一组特定条件中输入一个变量,以便在以后的计算中使用。即,它们不能超过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());
理论上有效值返回有效响应,高于vmax的值返回无效响应并请求用户重新输入。但是否定或字符串不会返回任何内容。
关于如何让它发挥作用的任何想法?
答案 0 :(得分:2)
您可以使用以下代码来实现您的目标。请注意,答案与此答案的答案非常相似:
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;
}
答案 1 :(得分:0)
首先这是C,而不是C#。
getchar
从标准输入读取,因此在每次迭代中,您调用(最多)3次getchar()并读取3次用户输入。所以你可以删除那些电话。
scanf
函数返回成功转换的次数,以便您可以使用此(== 1)检查用户是否未输入正确的浮点值。
编辑:我删除了代码,因为我无法在手机上编译,抱歉 使用fgets / atof,如本页http://www.cplusplus.com/reference/cstdlib/atof/
中的示例所示