佳礼资讯网

 找回密码
 注册

ADVERTISEMENT

查看: 1129|回复: 6

C++ next=='y'||'Y' and next=='y'||next=='Y'(已解决)

[复制链接]
发表于 4-2-2009 05:35 PM | 显示全部楼层 |阅读模式
情问一下,为什么这个cin>>n 能止while loop?
void main()
{
char next='y';
while(next=='y'||next=='Y')
{
cout<<" Pls enter \'y\' to continue, \'n\' to abort: ";
cin>>next;
}
cout<<"U had chosen to abort...";
getch();
}

换做while(next=='y'||'Y')却不能? 但两个cin>>y 或cin>>Y都没问题。。。
谢谢!

[ 本帖最后由 避风港的鱼 于 13-2-2009 05:32 PM 编辑 ]
回复

使用道具 举报


ADVERTISEMENT

发表于 4-2-2009 09:48 PM | 显示全部楼层
不是很明白你要问什么

while(next=='y'||next=='Y')
---> 如果next是 y 或 Y, 就一直不会出来

cin>>next;
--> 叫系统把键盘输入放进 next 这个variable 里面

while(next=='y'||'Y')
--> 永远出不来,因为 'Y' 有ASCII value (89); 变成好像你在写
while( 89 )
回复

使用道具 举报

 楼主| 发表于 5-2-2009 09:15 AM | 显示全部楼层
其实是这样:这是while(next=='y' || next=='Y')的output
Pls enter 'y' to continue, 'n' to abort: y
Pls enter 'y' to continue, 'n' to abort: Y
Pls enter 'y' to continue, 'n' to abort: n
U had chosen to abort...

而这是while(next=='y' || 'Y')的output
Pls enter 'y' to continue, 'n' to abort: y
Pls enter 'y' to continue, 'n' to abort: Y
Pls enter 'y' to continue, 'n' to abort: n
Pls enter 'y' to continue, 'n' to abort:

我不懂为何 ‘y’ 与 ‘Y‘ 在两种写法中都能继续while loop, 但 'n' 在第二种写法中却不能停止while loop...
回复

使用道具 举报

发表于 5-2-2009 11:22 AM | 显示全部楼层
while(next=='y' || 'Y')
是错误的写法。 || 是logical OR operator,它的作用是执行逻辑性OR的运算
  1. Logical OR Logic Table:
  2. Operand 1   Operand 2    Result
  3. ---------   ---------    ------
  4. 0           0            0
  5. 0           1            1
  6. 1           0            1
  7. 1           1            1
复制代码
在这里可以看到,Logical OR 是使用两个Operand来计算出结果,只要任何一个Operand的数值是1,其运算结果就是1(一般上1也代表True)。

当 Logical OR 被运用在 Loop 或者任何 Decision Making 时,它要求在 || 的两边的 Condition 都必须能够成立:
  1. while(condition1 || condition2)
  2. //While condition1 is True OR condition2 is True, the loop goes on.
复制代码
换句话说,|| 的两边都必须是可以计算出结果的运算式。

当你提供的任何一个运算式无法成立,Compiler 会默认其结果为 True (除非那个无法运算的运算式的默认数值是0,也就是False)。

你的运算式里面,nexy=='Y' 可以成立,当你按下 ’Y' 时,其运算结果为 True,反之则为False。

另一边,‘y' 这个很明显并不是一个运算式,所以compiler直接把它当作运算结果来 对待,'y' 在 ASCII 代码里面的数值是 121 (0x79),任何非0的数值都被当作 True 来对待,所以,你的 Operand 2 永远是 True,所以无论你按什么按键,这个永远是 True 的Operand会让你的 while loop 成为 infinite loop (永远无法解脱的轮回)。

你明白了吗?

[ 本帖最后由 geekman 于 5-2-2009 11:32 AM 编辑 ]
回复

使用道具 举报

发表于 11-2-2009 01:08 PM | 显示全部楼层

回复 4# geekman 的帖子

while(tolower(next) == 'y'){
...
}

会好一点吗?

[ 本帖最后由 asimo 于 11-2-2009 01:10 PM 编辑 ]
回复

使用道具 举报

发表于 11-2-2009 05:47 PM | 显示全部楼层

回复 5# asimo 的帖子

嗯,把使用者的输入转换成统一的case的确会比较好处理,只要你并不需要分开处理大写和小写的输入,就没问题。
回复

使用道具 举报

Follow Us
 楼主| 发表于 13-2-2009 05:31 PM | 显示全部楼层
我想我懂了,谢谢各位。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

 

ADVERTISEMENT



ADVERTISEMENT



ADVERTISEMENT

ADVERTISEMENT


版权所有 © 1996-2023 Cari Internet Sdn Bhd (483575-W)|IPSERVERONE 提供云主机|广告刊登|关于我们|私隐权|免控|投诉|联络|脸书|佳礼资讯网

GMT+8, 18-12-2025 06:11 AM , Processed in 0.159100 second(s), 24 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表