我试图弄清楚前测试循环还是后测试循环是最好的方法,以便用户可以继续输入将要搜索的值,直到输入一个哨兵值来结束程序。另外,我的循环参数是什么样的?这是我的代码,我需要包含循环。另外,我知道后测试循环至少执行一次。提前致谢!
#include<iostream>
using namespace std;
int searchList( int[], int, int); // function prototype
const int SIZE = 8;
int main()
{
int nums[SIZE]={3, 6, -19, 5, 5, 0, -2, 99};
int found;
int num;
// The loop would be here
cout << "Enter a number to search for:" << endl;
cin >> num;
found = searchList(nums, SIZE, num);
if (found == -1)
cout << "The number " << num
<< " was not found in the list" << endl;
else
cout << "The number " << num <<" is in the " << found + 1
<< " position of the list" << endl;
return 0;
}
int searchList( int List[], int numElems, int value)
{
for (int count = 0;count <= numElems; count++)
{
if (List[count] == value)
// each array entry is checked to see if it contains
// the desired value.
return count;
// if the desired value is found, the array subscript
// count is returned to indicate the location in the array
}
return -1; // if the value is not found, -1 is returned
}