#include <stdio.h>
int main(){
float x,y;
printf("Enter 2 numbers: \n");
scanf_s("%f %f", &x, &y);
if (getchar() == '\n')
{
printf("Division: %f\n", x / y);
printf("Product: %f\n", x * y);
printf("Sum: %f\n", x + y);
printf("Difference: %f\n", x - y);
}
else
{
printf("no Float-Value!");
}
getchar();
return 0;
}
我们需要一个循环,这样如果我们输入错误的格式,程序应该再次要求输入两个数字
最佳答案
检查输入有效性的最佳方法是检查 scanf_s
的返回值,它告诉您已成功设置的变量数。在你的情况下,如果它是 2 那么一切都很好;否则你需要重复。
换句话说
do {
int c;
while ((c = getchar()) != '\n' && c != EOF); // clear the input stream
printf("Enter 2 numbers: \n");
} while (scanf_s("%f %f", &x, &y) != 2);
是一个合适的控制结构,而不是 if (getchar() == '\n')
,您应该删除它。
关于c - 如何循环 scanf_s() 直到成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50840130/