喵宅苑 MewoGarden × 技术宅社区II | Z站 Z Station 棒棒哒纯文字二次元技术社区

正文

新手求助,关于一个switch的跳出问题

作者:阳光闪闪
[i=s] 本帖最后由 阳光闪闪 于 2015-7-31 10:26 编辑 c primer plus 第七章第11道习题,用的是DEV c++, 我写出来后每次进入switch不管跳到哪个case最后都会强行走一遍default再转下一个循环。。。,试过把continue换成break还是依然跳不过这个default,公司写代码的同事都搞不定。。。求大神指教我问题出在哪里TAT int main(void) { char choice,choice2; int artichoke, beet, carrot, buy, tart, tbee, tcar,allmess; float allprice,fprice,tprice; tart = tbee = tcar = 0; printf("Please choose the product you want to buy:(q to quit,y to count)\n"); printf("a) artichoke b) beet c) carrot \n"); first:while((choice=getchar()) != 'q') { switch(choice) { case 'a': printf("How many pounds do you want to buy: \n"); scanf("%d", &buy); tart += buy; continue; case 'b': printf("How many pounds beet do you want to buy: \n"); scanf("%d", &buy); tbee += buy; continue; case 'c': printf("How many pounds carrot do you want to buy: \n"); scanf("%d", &buy); tcar += buy; continue; default: printf("You have enter the wrong number, please enter a, b, c, y or q. \n"); goto first; } printf("Do you want to buy more?\n"); goto first; } printf("Thank you!"); over:return 0; }

回复

我居然看到了

作者:crackhopper
我居然看到了goto!!!
查看回复

你还需要对换行符进行特殊处理

作者:恋爱的镇魂曲
另外,你还需要对换行符进行特殊处理,在switch前面加一个 if(choice=='\n')continue;就可以 最后,为什么不写关于计算和显示价格的代码?
查看回复

是跳过本次循环

作者:恋爱的镇魂曲
continue是跳过本次循环break是跳出循环体 使用break吧
查看回复

虽然我不主

作者:bai200255
虽然我不主c/c++,但是按照java的习惯应该也不差。。。 我觉得是continue的问题,因为它并没有使循环跳出,推荐试试break;(至少java是这样) 不过你既然解决了……就算了……嘛
查看回复

番茄星人

作者:阳光闪闪
番茄星人 发表于 2015-7-31 21:21 剩下就是吐槽时间 程序里面用goto语法!!!!!这是很不好的!!!!不建议
感谢大神的帮助,问题已经成功解决,虽然代码也乱到要重写了。。。 PS:抱歉过了这么久才回复,帖子发完后跟着来了茫茫多的工作让我没时间搞这段错漏百出的的练习。。。
查看回复

剩下就是吐槽时间

作者:番茄星人
剩下就是吐槽时间 程序里面用goto语法!!!!!这是很不好的!!!!不建议 也不论goto问题了,你在switch里面用continue,continue只可以用在循环里面,虽然这里能发挥跟break一样的效果,但是这是BUG! 程序的结构很乱,建议考虑清楚程序逻辑结构重写,一个程序用到了goto语法就说明这个逻辑结构是很差的 还有一个,你公司写代码的同事竟然看不出这些问题来。。。#om
查看回复

首先先帮你解决问题

作者:番茄星人
首先先帮你解决问题 无法摆脱default是因为没有考虑到回车键的问题,回车键也算进输入的 加入我这样输入 Please choose the product you want to buy:(q to quit,y to count a) artichoke b) beet c) carrot -》y You have enter the wrong number, please enter a, b, c, y or q. You have enter the wrong number, please enter a, b, c, y or q. 会看到这样输出 首先输入的是y,当然会输出You have enter the wrong number, please enter a, b, c, y or q. 这句了 然而第二句是什么回事?我只输入了一个字母 因为还有回车键,也算上了 所以判断了两次 截下来 -》a How many pounds do you want to buy: -》2 You have enter the wrong number, please enter a, b, c, y or q. 截下来就出现你说的问题了 原因也是一样,其实我是一次性输入了 2 和回车键 它获取到2以后 运行 scanf("%d", &buy); tart += buy; 接着是continue; 会跳出switch 但是还有一个回车键,因此他会判断然后再次进去switch输出 You have enter the wrong number, please enter a, b, c, y or q. 换成break也是一样的我测试过,归根到底就是忽略了回车键的问题 怎么解决?在第二个switch前面加getchar()
查看回复
上一页
下一页
0%
站点地图友情链接:
喵宅苑
喵空间社区程序
喵宅苑 静态版
宅喵RPG地图编辑器
络合兔
Lanzainc
技术宅
小五四博客
莉可POI
Mithril.js
枫の主题社
Project1
午后少年
机智库
七濑胡桃
xiuno
幻想の日常
魂研社
Nothentai
0xffff
欲望之花
泽泽社长
淀粉月刊
HAYOU