2017-03-01 4 views
-1

平均値に最も近い値を得る方法は不思議で、ユーザーが入力した2つの範囲内でユーザーからの入力を取得して2D配列を出力します。それはまた、最小値と最大値を出力します(平均値はすべてコード化されています)。配列の中で最も近い値を平均値に、次に配列内の位置を返す関数を書く方法は不明です。平均値とその位置に最も近い値を取得する方法C

+0

あなたが行ったすべての試みを見て良いでしょう。 –

+1

また、 'fflush(stdin)'は未定義の動作をします。 – Peter

+0

@AjayBrahmakshatriyaのオリジナル投稿に可能な限り追加しましたが、そこからどこに行くのか分かりません – Luke

答えて

1
  1. 各要素から平均値を減算します。
  2. 結果の絶対値を取る。
  3. 差が最も小さい位置と要素を格納します。

    int fnFindClosestVal(int arn2DArray[][6], int nRows, int nCols, double nTotal, int *posRow, int *posCol) 
        { 
         int nClosestValue = arn2DArray[0][0]; 
         int nDiff = abs(arn2DArray[0][0] - nTotal); 
         int Row,Col; 
    
         for (nCountRows = 0; nCountRows < nRows; nCountRows++) 
         { 
          for (nCountCols = 0; nCountCols < nCols; nCountCols++) 
          { 
            if(abs(arn2DArray[nCountRows][nCountCols] - nTotal) < nDiff) 
            { 
             nDiff = abs(arn2DArray[nCountRows][nCountCols] - nTotal); 
             nClosestValue = arn2DArray[nCountRows][nCountCols]; 
             *posRow = nCountRows; 
             *posCol = nCountCols; 
            } 
          } 
         } 
        return nClosestValue; 
    } 
    
+0

これは大変感謝しています!最も近い値の位置を出力するにはどうすればいいですか? @Shihab – Luke

+0

@ルークこれに応じてコードを修正しました –

+0

私はprintf( "\ n平均に最も近い値は%6dで、場所は\ n"、fnFindClosestVal(arn2DArray、5、6、fnFindAverageValue(arn2DArray 、5,6)));この場所をprintfステートメント内に挿入する方法はありますか? – Luke

関連する問題