首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Switch语句中嵌套的if/else

问Switch语句中嵌套的if/else
EN

Stack Overflow用户
提问于 2012-09-26 15:50:34
回答 5查看 16.5K关注 0票数 3

我试图在case switch语句中嵌套一个if/else。当我输入大小写'p‘或'P’时,不管输入的是什么字符,都会打印出$15.00行。我已尝试移动/添加{}的,但输出没有变化。

感谢你抽出时间来帮助一个菜鸟。

这里有完整的代码。

代码语言:javascript
复制
#include <stdio.h>

int main()
{
//variable declarations 
char typeOfWash, tireShine;

//Menu
printf("R ---> Regular ($5.00)\n");
printf("B ---> Bronze ($7.50)\n");
printf("G ---> Gold ($10.25)\n");
printf("P ---> Platinum ($15.00)\n");
printf("Tire Shine can be added to the Gold or Platinum ONLY,");
printf("for an additional$2.50\n\n");

printf("Enter your selection: ");
scanf("%c",&typeOfWash);

switch (typeOfWash)
{
    case 'R': case 'r':
        printf("Your bill total is: $5.00\n");
        break;
    case 'B': case 'b':
        printf("Your bill total is: $7.50\n");
        break;
    case 'G': case 'g':
        printf("Would you Like a Tire Shine? (Y/N): ");
        scanf("%c ",&tireShine);
        if (tireShine == 'Y' || tireShine == 'y')
            printf("Your bill total is: $12.75\n");
        else
            printf("Your bill total is: $10.25\n");
        break;
    case 'P': case 'p':
        printf("Would you Like a Tire Shine? (Y/N): ");
        scanf("%c ",&tireShine);
        printf("%c",tireShine);
        if (tireShine == 'Y' || tireShine == 'y')
            printf("Your bill total is: $17.50\n");
        else
            printf("Your bill total is: $15.00\n");
        break;
    default:
        printf("Invalid Choice");

}
return 0;
}
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-09-26 16:56:19

问题是,使用带有%c格式说明符的scanf会导致空白空间不会被使用,在本例中,这会导致在输入缓冲区中留下一个\n。你的讲师似乎建议在下一个scanf中去掉初始输入中的尾随空格;然而,我怀疑他们说插入前导空格而不是尾随空格,因为这解决了您的问题:

代码语言:javascript
复制
scanf(" %c", &tireShine);

或者,您可以在第二个scanf之前立即使用getchar(),并预先使用换行符:

代码语言:javascript
复制
getchar();
scanf("%c", &tireShine);

第二种选择是使用%s格式说明符代替%c,并相应地处理它。

需要注意的是,getchar()将只使用输入缓冲区中的一个字符。例如,如果用户要输入一个长度超过1个字符的字符串,则需要使用类似于while ((x = getchar()) != '\n') ;的内容来清除缓冲区。

票数 2
EN

Stack Overflow用户

发布于 2012-09-26 15:58:44

尝试内联if。

代码语言:javascript
复制
case 'P': case 'p':
    printf("Would you Like a Tire Shine? (Y/N): ");
    scanf("%c",&tireShine);
    printf("Your bill total is: $%s\n", toUpper(tireShine) == 'Y' ? "17.50":"15.00");
    break;
票数 0
EN

Stack Overflow用户

发布于 2012-09-26 15:59:50

你还有一个空间。

变化

代码语言:javascript
复制
scanf("%c ", &tireShine);

至

代码语言:javascript
复制
scanf("%c", &tireShine);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12596994

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档