我试图构建一个使用来自用户的输入的小程序,然后使用开关盒执行适合用户输入的操作。
我一直在努力寻找我的程序有什么问题,但没有运气很明显我少了一些东西。
这是密码,你能帮我找出它的毛病吗?

#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
与scanf和wscanf不同,scanf和wscanf需要缓冲区大小
为c、c、s、s或字符串类型的所有输入参数指定
包含在[]中的控件集以字符为单位的缓冲区大小为
作为附加参数传递,紧跟在指向
缓冲区或变量
还应检查错误,因此应:

char fuel;
if (scanf_s("%c", &fuel, 1) != 1)  {
    puts("Error from scanf_s");
    return 1;
}

关于c - 该程序将跳过所有切换情况下的情况,并转到默认情况,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33890402/

10-17 01:50