#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;
}
Run Code Online (Sandbox Code Playgroud)
我们需要得到一个循环,所以如果我们输入错误的格式,程序应该再次要求输入两个数字
检查输入有效性的最佳方法是检查返回值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);
Run Code Online (Sandbox Code Playgroud)
是一个合适的控制结构,而不是if (getchar() == '\n')你应该放弃的.