当用户输入具有值时,以某种方式绕过了条件

else condition get's somehow bypassed when the user input has a value

本文关键字:方式绕 条件 过了 输入 用户      更新时间:2023-10-16

所以我正在尝试制作一个反复要求用户猜测数字的程序。然后,如果满足以下条件之一,他将失败(或程序退出):

  • 用户使用数字 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){

计算到trueelse部分永远不会被执行。如果您希望执行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>时,您才会退出循环。而且您还需要注意负数。