【问题标题】:Why does the compiler skip my while statement?为什么编译器会跳过我的 while 语句?
【发布时间】:2019-12-02 02:34:44
【问题描述】:

这是我为练习 C++ 而开发的一个简单而愚蠢的循环练习。

这里的问题是当我在终端中手动输入“h”时,我希望看到我在if 循环中构建的输出。但是,终端返回 while 循环。我怀疑这是因为我误用了数据类型,虽然我不确定。

这是我写的:

#include <iostream>
using namespace std;

int main() { 

char letter;
int attempts = 0;
char h;

cout << "Welcome user.\n\n";
cout << "Before we begin,\n";
cout << "might I ask what your favorite letter is?\n";
cout << "For arbitrary reasons only.\n\n";
cin >> letter;




  while (letter !=h && attempts <= 2) {
      cout << "That is a sad letter\n";
      cout << "and not the kind of letter we're looking for here.\n";
      cout << "Please choose another.\n\n";
      cin >> letter;
      attempts++;
  }

  if (letter == h) {
      cout << "Ah, what a wonderful letter.\n";
      cout << "Let us continue on and not worry ourselves with such trivial matters\n";
  }

}

【问题讨论】:

  • 您正在使用一个名为 h 的变量。 h的值是多少?
  • 就是这样。我想说“h”是“正确”最喜欢的字母。因此,如果有意义的话,我相信 'h' 的值将是 0 或它本身。
  • 变量h 中的垃圾值不确定。使用它会使您的代码具有未定义的行为。
  • 变量h与字符'h'不同。

标签: c++ loops while-loop logic


【解决方案1】:

您需要在 while 循环和 if 语句中的“h”周围加上单引号,或者将“h”分配给变量(char h = 'h')。只做其中之一,不要两者都做,否则它们会相互抵消。 希望这会有所帮助。

【讨论】:

    【解决方案2】:

    你需要给 h 一个值才能让它工作。例如 char h = 'h';

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      相关资源
      最近更新 更多