C语言关于break依旧会输出同列的printf

YLemon 2016-10-06 05:00:40
源代码如下:
#include<stdio.h>
int main()
{
int result=rand()%101; //随机赋值
int guess;
char ch;
printf("please input number between 1 and 100:");
while(1)
{
scanf("%d",&guess);
if(guess > result) //猜的数字大了
{
printf("You guess number is too big.\n");
printf("please input number between 1 and 100:");
}
if(guess < result) //猜的数字小了
{
printf("You guess number is too small\n");
printf("please input number between 1 and 100:");
}
if(guess == result) // 正确
{
printf("Bingo!\n");
printf("Do you want to quit? Y/N.\n");
scanf("%c",&ch);
if(ch == 'Y')
break;
else if(ch=='N')
printf("please input number between 1 and 100:");
continue;
}
}
}
为什么,通过‘Y’退出之后,依旧会输出
“Bingo!
Do you want to quit? Y/N.”

烦请各位解释一下原因,以及如何修改源代码,谢谢!
...全文
107 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
paschen 2016-10-06
  • 打赏
  • 举报
回复
#include<stdio.h>
int main()
{
	int result=rand()%101;   //随机赋值
	int guess;
	char ch;
	printf("please input number between 1 and 100:");
	while(1)
	{
		scanf("%d",&guess);
		getchar();
		if(guess > result)      //猜的数字大了
		{
		printf("You guess number is too big.\n");
					printf("please input number between 1 and 100:");
		}
		if(guess < result)     //猜的数字小了
		{
			printf("You guess number is too small\n");
			printf("please input number between 1 and 100:");
		}
		if(guess == result)    // 正确
		{
			printf("Bingo!\n");
			printf("Do you want to quit? Y/N.\n");
			scanf("%c",&ch);
			if(ch == 'Y')
				break;
			else if(ch=='N')
				printf("please input number between 1 and 100:");
			continue;
		}
	}
}
paschen 2016-10-06
  • 打赏
  • 举报
回复
scanf("%c",&ch); 会接收了你上一次输入完后的换行符 \n 在scanf("%d",&guess);后面加上getchar();即可
ooolinux 2016-10-06
  • 打赏
  • 举报
回复
printf("Bingo!\n"); printf("Do you want to quit? Y/N.\n"); scanf("%c",&ch); if(ch == 'Y') break; 你的顺序不是这样吗?

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧