| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 624 人关注过本帖
标题:关于这个 while 为何会循环打印 2 次
只看楼主 加入收藏
ctl184762651
Rank: 1
等 级:新手上路
帖 子:56
专家分:0
注 册:2014-5-31
结帖率:93.75%
收藏
 问题点数:0 回复次数:6 
关于这个 while 为何会循环打印 2 次
程序代码:
#include<stdio.h>
int main(void)
{   
int guess=1;
printf("Uh..is your number %d?\n",guess); 

    while(getchar()!='y')
    
    printf("Well,then,is it %d?\n",guess++);

printf("i konw i could do it\n");

return 0;
}

首先打印Uh..is your number 1
然后要求输入,如果等于Y,打印i konw i could do it
如果等于N,打印Well,then,is it %d?
假如如下
Uh..is your number 1?
键入n
Well,then,is it 2?
n
Well,then,is it 3?
y
i konw i could do it
这个是预期结果,可是为什么每次输入N后就连续打印2次
Well,then,is it 2?
Well,then,is it 3?
n
Well,then,is it 4?
Well,then,is it 5?
搜索更多相关主题的帖子: guess 
2014-09-11 23:07
Coincedence4
Rank: 3Rank: 3
等 级:论坛游侠
帖 子:52
专家分:151
注 册:2014-9-4
收藏
得分:0 
while(getchar()!='y')
 { printf("Well,then,is it %d?\n",++guess);getchar();}
或者
while(getchar()!='y'&&getchar()!=NULL)
 printf("Well,then,is it %d?\n",++guess);
2014-09-11 23:41
sand6174
Rank: 2
等 级:论坛游民
威 望:1
帖 子:13
专家分:15
注 册:2014-9-4
收藏
得分:0 
因为getchar是从流中得到一个字串~~你输入的时候还有个回车~~
2014-09-12 10:13
sand6174
Rank: 2
等 级:论坛游民
威 望:1
帖 子:13
专家分:15
注 册:2014-9-4
收藏
得分:0 
回复 3 楼 sand6174
是字符
2014-09-12 10:14
陈宇水
Rank: 2
来 自:东莞
等 级:论坛游民
帖 子:29
专家分:34
注 册:2013-5-5
收藏
得分:0 
因为getchar()每次只能接受一个字符,你的回车也算一个的,所以返回两个结果
函数可以改为下面的就可以啦#include<stdio.h>
 int main(void)
 {   
 int guess=1;
 printf("Uh..is your number %d?\n",guess);

    while(getchar()!='y')
     
    {
        printf("Well,then,is it %d?\n",guess++);
        if(getchar()=='\n')
            continue;
    }

printf("i konw i could do it\n");
 
return 0;
 }

我是一个C语言初学者
2014-09-12 10:51
南山浅悠然
Rank: 2
等 级:论坛游民
威 望:1
帖 子:53
专家分:92
注 册:2014-5-21
收藏
得分:0 
#include<stdio.h>
int main(void)
{
int guess = 1;
char ture = 'I konw I could do it';
printf("Uh..is your number%d?\n",guess);
if
{
    while(getchar() = "n")
    printf("When,then,is it%d\n ",guess++);
}
else if
{
    scanf = ("y");
    putchar("ture\n");
}
return 0;
}
2014-09-12 11:13
fogmaple
Rank: 4
来 自:江西省赣州市于都县
等 级:业余侠客
威 望:1
帖 子:119
专家分:233
注 册:2014-7-28
收藏
得分:0 
回车了两下
2014-09-12 12:51
快速回复:关于这个 while 为何会循环打印 2 次
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.027055 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved