1

プログラムを終了するためにセンチネル値が入力されるまで、ユーザーが検索される値を入力し続けることができるように、テスト前ループまたはテスト後ループが最適な方法であるかどうかを判断しようとしています。また、ループのパラメータはどのようになりますか? これが私のコードです。ループを含める必要があります。また、ポスト テスト ループが少なくとも 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 回 (1 回以上) ループを実行する必要がある場合

前例: ループは 0 回以上実行できます。

于 2013-11-18T19:02:45.217 に答える
1

私はあなたが何を知りたいのか完全にはわかりません。正直なところ、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;
 }
于 2013-11-18T18:59:22.997 に答える