如何检索最接近的值及其位置C



我只是想知道如何获得与均值的最接近值,程序从用户中检索输入,然后在两个范围内输出一个2D数组,范围为用户输入。然后,它还输出最低和最高的数组值,平均值(所有这些都已编码),我只是不确定如何编写函数以返回数组中的最接近值,然后返回数组中的位置。

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

最新更新