[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; }
首先先帮你解决问题 无法摆脱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()查看回复