当用户输入具有值时,以某种方式绕过了条件
else condition get's somehow bypassed when the user input has a value
所以我正在尝试制作一个反复要求用户猜测数字的程序。然后,如果满足以下条件之一,他将失败(或程序退出):
- 用户使用数字 5
- 用户使用大于 10 的数字
- 用户使用的数字等于他已经猜到的猜测次数
- 用户只有 10 次尝试
这就是问题所在,如果我输入数字 5 作为我的第一个猜测,else 函数工作并且 cout 输出字符串,但如果我先猜测其他内容,然后出于某种原因使用数字 5,程序就会退出而不输出字符串在最后一个 else 块中。
这是我很想看到一些关于我需要更改的内容的反馈,以便我可以输入多个用户输入,然后仍然是数字 5 来获取 else 函数中的 cout 字符串。提前谢谢你:)
这是代码:
#include <iostream>
using namespace std;
int main() {
int input = 0;
short counter = 0;
cout << "Hello fellow PC-User why don't you guess a number that is between 1-10 ?" << endl;
cout << "Come on give it a try!nOnly two conditions (maybe three) don't use the Number 5 and only Numbers 1-10!nNow let's go!!!" << endl;
cin >> input;
if(input != 5 && input < 10){
while(input != 5 && input < 10) {
++counter;
cout << "Nice you guessed " << counter << flush;
if (input > 1){
cout <<" times!" << flush;
} else{
cout << " time!" << flush;
}
cout << "nNow go at it again just don't used the number the times u tried bro!" << endl;
cin >> input;
if(counter == 10){
cout << "Damn that motivation doe...well what can I sayn I give up n U win." << endl;
return 0;
} else if(counter == input){
cout << "Don't do it..." << endl;
return 0;
}
}
} else {
cout << "Yo! You weren't supposed to use that number!nNow u looooose" << endl;
}
return 0;
}
块
的else
部分不会在if
块内的while
循环中调用。
如果您的第一个输入正确,即条件
if(input != 5 && input < 10){
计算到true
,else
部分永远不会被执行。如果您希望执行else
块,无论 if
语句的条件何时计算为 false,则需要以稍微不同的方式重新组织if
块和while
循环。
// Simple conditional.
// Loop forever until a break statement in the loop breaks the loop.
while(true ) {
if(input != 5 && input < 10){
++counter;
cout << "Nice you guessed " << counter << flush;
if (input > 1){
cout <<" times!" << flush;
} else{
cout << " time!" << flush;
}
cout << "nNow go at it again just don't used the number the times u tried bro!" << endl;
cin >> input;
if(counter == 10){
cout << "Damn that motivation doe...well what can I sayn I give up n U win." << endl;
return 0;
} else if(counter == input){
cout << "Don't do it..." << endl;
return 0;
}
} else {
cout << "Yo! You weren't supposed to use that number!nNow u looooose" << endl;
// Provide a way to break out of the while loop.
break;
}
}
外部 if 条件确实不需要,因为它只会在第一次执行。只需在 while 循环之后移动 if-else 部分,看看会发生什么。实际上,如果根本不需要条件,因为只有在输入 == 5 或输入 10>时,您才会退出循环。而且您还需要注意负数。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 如何在c++中为模板函数实例创建快捷方式
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 使用逻辑 AND (&&) 时,如何以编程方式查看C++中不满足哪些条件?
- 优雅的方式,将初始化器移动到有条件的循环后面
- 操作员对()的过载及其可以使用的不同方式和条件
- 不同的条件检查方式
- 绕Y轴旋转二维正方形,并使用DirectX或openGL以透视投影方式显示
- 逗号(,)在条件部分中两个表达式之间的for循环中的工作方式
- 编写有条件可选构造函数的最佳方式
- 当某个条件为真时,如何在 Eclipse 中以编程方式设置C++断点
- 我如何以相同的方式对两个向量排序,而条件只使用其中一个向量
- 如何以标准方式组合来自type_traits的条件
- 用指针写条件的几种方式的区别
- 有条件地使用RAII的最佳方式
- 当用户输入具有值时,以某种方式绕过了条件