需要帮助,以停止程序终止,无需用户同意 [英] Need help to stop program terminating without users consent
问题描述
下面的代码应该如下:
-
创建用户指定的列表
create list specified by the user
要求用户输入号码
ask user to input number
<在列表中,显示数字* 2,返回到步骤2
3.a) if number is on the list , display number * 2, go back to step 2
3.b)如果数字不在列表上,终止程序
3.b) if number isn't on the list, terminate program
然而,步骤3.a)也会终止程序,这会破坏while循环的目的。
HOWEVER step 3.a) will also terminate the program, which is defeating the purpose of the while loop.
代码:
#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;
}
有人可以帮我解决这个问题吗?
Please can someone help me to resolve this ?
推荐答案
我建议您将步骤3的功能封装到单独的函数中。你可以如下定义一个函数,然后在main函数的适当位置调用它。
I would suggest that you encapsulate the functionality of step 3 into a separate function. You could define a function as follows, and then call it at an appropriate location in the main function.
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
被认为是不好的做法,我不会推荐它。
The same functionality can be implemented with a goto
statement, avoiding the need for a function. However, using goto
is considered bad practice and I won't recommend it.
这篇关于需要帮助,以停止程序终止,无需用户同意的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!