需要帮助来阻止程序在未经用户同意的情况下终止

Need help to stop program terminating without users consent

下面的代码应该做如下:

  1. 创建用户指定的列表

  2. 要求用户输入数字

3.a) 如果数字在列表中,则显示数字 * 2,返回步骤 2

3.b) 如果号码不在列表中,终止程序

HOWEVER 步骤 3.a) 也会终止程序,这违背了 while 循环的目的。

这是代码:

#include <iostream>
#include <array>
using namespace std;
int main()
{
cout << "First we will make a list" << endl;

array <int, 5>list;
int x, number;
bool isinlist = true;

cout << "Enter list of 5 numbers." << endl;

for (x = 0; x <= 4; x++)
{
    cin >> list[x];
}
while (isinlist == true)
{
    cout << "now enter a number on the list to double" << endl;
    cin >> number;

    for (x = 0; x <= 4; x++)
    {
        if (number == list[x])
        {
            cout << "The number is in the list. Double " << number << " is " << number * 2 << endl;
        }
        else
            isinlist = false;
    }
}
return 0;
}

有人可以帮我解决这个问题吗?

我建议您将步骤 3 的功能封装到一个单独的函数中。您可以如下定义一个函数,然后在主函数中的适当位置调用它。

void CheckVector(vector<int> yourlist)
{
  .... // Take user input for number to search for
  .... // The logic of searching for number. 
  if (number exists)
  {
    // cout twice the number
    // return CheckVector(yourlist)
  }
  else
    return;
}

相同的功能可以用 goto 语句实现,避免了对函数的需要。但是,使用 goto 被认为是不好的做法,我不会推荐它。

您的问题是,一旦列表中的单个值不等于用户输入,您就将 isinlist 设置为 false。

您应该在 while 循环开始时将 isinlist 设置为 false,如果找到匹配则将其更改为 true。

使用调试器单步执行代码应该有助于您理解问题。我鼓励你尝试一下。