c++ - 前或后测试循环?

标签 c++ arrays loops 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
  }

最佳答案

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

后用例:当您需要循环至少运行一次(1 次或多次)

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

关于c++ - 前或后测试循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20055376/

相关文章:

c++ - 带有 RRF_RT_REG_SZ 的 RegSetValueEx 在注册表中生成 REG_EXPAND_SZ?

arrays - 变量矩阵 NumPy 的值

php - 从 MySQL 单元内部循环 PHP 创建变量

javascript - ExtJS - 如何遍历商店并获取在特定列中找到的每个项目的总数

c++ - GCC -Wunused-function 不起作用(但其他警告有效)

c++ - 自定义流实用程序

c++ - 错误 : no match for 'operator=' in 'iter = ((const FHlist<Employee>*)theList)->FHlist<Object>::begin [with Object = Employee]()'

c - C中的数组指针和指针数组

java - 在 Java 中打印二维构造函数

java - java 如何退出for循环?