1

我试图弄清楚前测试循环还是后测试循环是最好的方法,以便用户可以继续输入将要搜索的值,直到输入一个哨兵值来结束程序。另外,我的循环参数是什么样的?这是我的代码,我需要包含循环。另外,我知道后测试循环至少执行一次。提前致谢!

#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
  }
4

2 回答 2

3

您的问题更多地取决于用例。

Post Case:当您需要循环至少运行一次(1次或多次)时

Pre Case:循环可以运行 0 次或更多次。

于 2013-11-18T19:02:45.217 回答
1

我必须说,我不完全确定你想知道什么。老实说,我会推荐一本关于 C++ 的好书。后测试循环在 C++ 中不是很流行(它们的形式是“do..while”,其中“while”循环/预测试循环更为常见)。此处提供了更多信息:“再玩一次 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;
 }
于 2013-11-18T18:59:22.997 回答