我试图弄清楚测试前或测试后循环是否是最好的方法,以便用户可以继续输入将被搜索的值,直到输入sentinel值来结束程序。另外,我的参数对循环来说是什么样的?这是我的代码,我需要包含循环。另外,我知道后测试循环至少执行一次。提前致谢!
#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
}
答案 0 :(得分:3)
您的问题更多是依赖于用例。
发布案例:当您需要循环至少运行一次(1次或更多次)时
前例:循环可以运行0次或更多次。
答案 1 :(得分:1)
我必须说,我不完全确定你想知道什么。我诚实地推荐a good book on C++。后测试循环在C ++中并不常用(它们的形式为“do .. while”,其中“while”循环/预测试循环更常见)。这里提供了更多信息:"Play It Again Sam"
编辑:你需要从用户那里获取数据,测试它,然后根据它做一些事情。
是最好的选择 static const int SENTINEL = ??;
int num;
cout << "please input a number" << endl;
cin >> num;
while( num != SENTINEL ) {
// DO STUFF HERE
// Now get the next number
cout << "please input a number" << endl;
cin >> num;
}