我正在尝试构建一个使用用户输入的小程序,然后使用 switch case 执行适合用户输入的操作。 我一直在努力寻找我的程序中的错误,但没有运气。显然我缺少一些东西。
这是代码,你能帮我看看它有什么问题吗?
#include <stdio.h>
#define A 8.5
#define B 7.6
#define C 7.7
#define D 7.7
int main ()
{
char fuel;
float amount,total;
printf("please enter the desired fuel\n");
scanf_s("%c",&fuel);
switch(fuel)
{
case 'A' :
printf("how many liters of fuel do you want?\n");
scanf_s("%f",&amount);
total=amount*A;
if(total>150)
{
printf("the total price to pay is %.3f: \nYou have won a newspaper", total);
}
else
printf("the total price to pay is %.3f", total);
break;
case 'B' :
printf("how many liters of fuel do you want?\n");
scanf_s("%f",&amount);
total=amount*B;
if(total>150)
printf("the total price to pay is %f: \nYou have won a newspaper", total);
else
printf("the total price to pay is %.3f", total);
break;
case 'C' :
printf("how many liters of fuel do you want?\n");
scanf_s("%f",&amount);
total=amount*C;
if(total>150)
printf("the total price to pay is %f: \nYou have won a newspaper", total);
else
printf("the total price to pay is %.3f", total);
break;
case 'D' :
printf("how many liters of fuel do you want?\n");
scanf_s("%f",&amount);
total=amount*D;
if(total>150)
printf("the total price to pay is %f: \nYou have won a newspaper", total);
else
printf("the total price to pay is %f", total);
break;
default:
printf("no\n");
break;
}
}
即使我输入“A”、“B”、“C”或“D”,它也会使用默认值,而不是适当的大小写。 感谢您的帮助。
最佳答案
您没有正确使用scanf_s
函数。根据其documentation :
Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.
并且还应该检查错误,所以你应该这样做:
char fuel;
if (scanf_s("%c", &fuel, 1) != 1) {
puts("Error from scanf_s");
return 1;
}
关于c - 程序跳过 switch case 中的所有 case 并转到 default,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33890402/