【发布时间】:2016-02-26 16:50:58
【问题描述】:
我正在尝试构建一个使用用户输入的小程序,然后使用 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”,它也会进入默认值,而不是适当的大小写。 感谢您的帮助。
【问题讨论】:
-
您是否尝试过使用调试器?用一个来解决诸如此类的问题是微不足道的。
-
在这里可以正常工作。你确定你输入的是
A而不是'A'或a? -
请注意,这似乎是特定于 MS 特定的
scanf_s()函数。使用scanf()有效(使用 VS 12 检查)。但是,您应该 avoid using thescanf()family at all and use something like fgets() instead - 阅读整行并解析/处理应用程序中的输入。 -
您必须阅读手册页:"与 scanf 和 wscanf 不同,scanf_s 和 wscanf_s 需要为 c、C、s、S 等类型的所有输入参数指定缓冲区大小。 .." 所以你缺少一个参数
scanf_s("%c",&fuel);应该是scanf_s("%c",&fuel, 1); -
@GabrielMichaeli 我们可以看到,您被要求查看似乎行为不端的变量的 实际 值,因为它显然不是您的 认为应该是。
标签: c switch-statement