下面的代码应该做如下:
创建用户指定的列表
要求用户输入数字
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 的功能封装到一个单独的函数中。您可以按如下方式定义一个函数,然后在主函数中的适当位置调用它。
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
被认为是不好的做法,我不会推荐它。
关于c++ - 需要帮助来阻止程序在未经用户同意的情况下终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36111096/