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

Need help to stop program terminating without users consent

本文关键字:情况下 终止 程序 用户 帮助      更新时间:2023-10-16

以下代码应执行以下操作:

  1. 创建用户指定的列表

  2. 要求用户输入号码

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

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

然而,步骤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 的功能封装到一个单独的函数中。您可以按如下方式定义一个函数,然后在 main 函数中的适当位置调用它。

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 ay,如果找到匹配项,则应将其更改为 true。

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