while循环中的条件语句 [英] conditional statement in while loop

查看:183
本文介绍了while循环中的条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定错过了什么。我正在做一个练习学习c + +,它要求,如果用户输入c,p,t或g字符然后继续,否则重新请求提示,所以我写道:

I must have missed something. I'm doing an exercise to learn c++ and it asks that if a user inputs either c,p,t or g character then carry on, otherwise re-request prompt, so I wrote this:

#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int main(void){
  cout << "Please enter one of the following choices:" << endl;
  cout << "c) carnivore\t\t\tp) pianist\n";
  cout << "t) tree\t\t\t\tg) game\n";
  char ch;
  do{
    cout << "Please enter a c, p, t, or g: ";
    cin >> ch;
    cout << "\"" << ch << "\"" << endl;
  }while(ch != 'c' || ch != 'p' || ch != 't' || ch != 'g');

  cout << "End" << endl;

  cin.clear();
  cin.ignore();
  cin.get();

  return 0;
}

这不工作,我得到的是提示重新请求它

This does not work and all I get is the prompt re-requesting it even when pressing either of the correct characters.

但是如果我更改这一行:

However if I change this line:

while(ch != 'c' || ch != 'p' || ch != 't' || ch != 'g');

while(ch != 'c' && ch != 'p' && ch != 't' && ch != 'g');

为什么?我的理解是,OR语句应该作为一个测试是正确的。

why is that? My understanding is that the "OR" statement should work as one of the tests is correct.

推荐答案


为什么?我的理解是,OR语句应该作为一个测试是正确的。

why is that? My understanding is that the "OR" statement should work as one of the tests is correct.

总有个测试之一通过。字符不是'c',或者不是'p'。它不能同时是'c''p'。因此条件总是为真,导致无限循环。

Exactly. There is always one of the tests that passes. A character will either be not 'c', or not 'p'. It can't be both 'c' and 'p'. So the condition is always true, leading to an infinite loop.

连接符的替代条件,因为一旦 ch 等于其中一个替代项:其中一个不等式为假,因此整个条件为假。

The alternative condition with the conjunctions works because it is false as soon as ch is equal to one of the alternatives: one of the inequalities is false, and thus the whole condition is false.

这篇关于while循环中的条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆