【问题标题】:discount value cannot calculate after case commadcase 命令后无法计算折扣值
【发布时间】:2021-10-02 03:50:20
【问题描述】:

我的作业有问题。这就是它的样子

#include<stdio.h>
int main()
{
    char code;
    int price,discount;
    float total;
    printf("Please input price: ");
    scanf("%d",&price);
    printf("Please input discount code: ");
    scanf(" %c",&code);
    switch(code)
    {
        case 'a':   printf("Your discount code is 25 percent\n");
                    discount = 25;
                    break;
        case 'b':   printf("Your discount code is 15 percent\n");
                    discount = 15;
                    break;
        case 'c':   printf("Your discount code is 5 percent\n");
                    discount = 5;
                    break;
        default:    printf("Wrong code,Your discount is 0 percent\n");
                    discount = 0;
                    break;
    }
    total = (price*((100-discount)/100));
    printf("Your price is = %.2f\n",total);
}

我有 2 个问题要问

  1. 我的任务是我必须同时输入折扣代码的大写和小写字母(只有三个代码:a、b、c),那么如何将它们都放在 case 命令中? (这里我只做小写字母)

  2. 我已经运行了这个。但是当我最终尝试将其用于计算时,折扣值似乎为 0。当我只打印折扣时,它可以正常工作。我该如何解决?

对不起,我的英语很差,感谢您的帮助!

【问题讨论】:

标签: c++ codeblocks division integer-division


【解决方案1】:

会有不同的可能性。

scanf(" %c",&code);
switch(code)
{
    case 'a':
    case 'A':
      printf("Your discount code is 25 percent\n");
      discount = 25;
      break;

或者你在 switch 之前或之中将输入更改为小写!

switch( code | 0x60 ) // make it to lower case

这样您就不必更改以下代码。

【讨论】:

  • 如果我试图阅读带有code | 0x60的switch语句的代码,我可能会卡在那里一段时间。
  • 我更喜欢第一个可读性建议。
  • @whiskyo:抱歉,我没明白你的意思?
  • 0x60 的值不知从何而来,这是我第一次看到这样的用法。正因为如此,代码的可读性不是很好。
  • @wikeyo:是的,可读性并没有因此而提高...您可以使用定义#define LOWERCASE_BIT 0x60 并使用它。那么可读性要好得多。
猜你喜欢
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
  • 2016-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多