【发布时间】: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