【问题标题】:Pre or Post test loop? [closed]前或后测试循环? [关闭]
【发布时间】:2013-11-18 18:45:48
【问题描述】:

我正在尝试确定测试前循环还是测试后循环是否是最佳方法,以便用户可以继续输入将要搜索的值,直到输入标记值以结束程序。另外,我的循环参数是什么样的?这是我的代码,我需要包含循环。另外,我了解后测试循环至少执行一次。提前致谢!

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

【问题讨论】:

  • int++ 不会编译。
  • if (int i=0; num &gt; 0; int++) 你的意思是for(...)?我发现学习语言的最佳方法是购买good book,并完成练习。如果您能更好地掌握基础知识,您将更有机会回答自己的问题。
  • 在为num赋值之前,您还要检查num &gt; 0
  • @ZacHowland 我知道,我试图弄清楚前循环或后循环是否可行并且正在做猜测工作,我将编辑并删除该尝试
  • 是的,在提供实际代码时,通常最好确保它实际编译,否则您的意图不清楚。例如,您的“if (int i=0;num > 0;int++)”行需要括号,否则它下面的“cin”行将不是该条件的一部分,其次它不应该是“while(num != SENTINEL)" 还是什么?

标签: c++ arrays loops sentinel


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的帮助!
【解决方案2】:

我必须说,我不完全确定你想知道什么。老实说,我会推荐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;
 }

【讨论】:

  • 感谢您的帮助!我真的很感激!
  • 还有一件事,当我尝试使用 while 循环并使用 -99 作为 SENTINEL 时,直到我输入另一个数字然后它才退出,循环才退出。这是为什么呢?
  • 这与你检查num的值有关;我更新了上面的代码,这可能会有所帮助。
猜你喜欢
  • 2017-10-31
  • 1970-01-01
  • 2019-03-23
  • 2017-01-10
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
  • 2022-01-24
相关资源
最近更新 更多