c语言 switch (choice),c语言while与switch的嵌套

本文详细讲解了如何在C程序中修正choice变量类型,以正确处理用户输入的1-4选项,并介绍了两种修改方法:一是将choice改为char类型,直接处理字符输入;二是保持int类型,通过scanf接收并验证输入。同时,文中还强调了如何优雅地实现程序退出机制。
摘要由CSDN通过智能技术生成

满意答案

00e27ab806e4881f8254fe7ae8741834.png

Ridere

2017.01.11

00e27ab806e4881f8254fe7ae8741834.png

采纳率:59%    等级:9

已帮助:2369人

你的choice类型不对,有两种修改方式

1. 把choice改成char型,switch中case换成字符:#include

int main(void)

{

char choice;

while ((choice=getchar()) != '#')

switch (choice)

{

case '1':

printf("you choice one.\n");

break;

case '2':

printf("you choice two.\n");

break;

case '3':

printf("you choice three.\n");

break;

case '4':

printf("you choice four.\n");

break;

default:

printf("you choice quit.\n");

break;

}

printf("you have quit the program.\n");

getchar();

getchar();

return 0;

}

2. choice还是int型,用scanf输入choice,输入0结束#include

int main(void)

{

int choice;

scanf("%d", &choice);

while (choice != 0) {

switch (choice)

{

case 1:

printf("you choice one.\n");

break;

case 2:

printf("you choice two.\n");

break;

case 3:

printf("you choice three.\n");

break;

case 4:

printf("you choice four.\n");

break;

default:

printf("you choice quit.\n");

break;

}

scanf("%d", &choice);

}

printf("you have quit the program.\n");

getchar();

getchar();

return 0;

}

00分享举报

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值