finding closest value in an array

前端 未结 6 1906
情歌与酒
情歌与酒 2020-11-27 20:56
int[] array = new int[5]{5,7,8,15,20};

int TargetNumber = 13;

For a target number, I want to find the closest number in an array. For example, whe

6条回答
  •  天涯浪人
    2020-11-27 21:30

    If you need to find the closest value to the average

    very open style

    public static double Miidi(double[] list)
    {
        bool isEmpty = !list.Any();
        if (isEmpty)
        {
            return 0;
        }
        else
        {
            double avg = list.Average();
            double closest = 100;
            double shortest = 100;
            {
                for ( int i = 0; i < list.Length; i++)
                {
                    double lgth = list[i] - avg;
                    if (lgth < 0)
                    {
                        lgth = lgth - (2 * lgth);
                    }
                    else
                        lgth = list[i] - avg;
    
                    if (lgth < shortest)
                    {
                        shortest = lgth;
                        closest = list[i];
                    }
                }
            }
    
            return closest;
        }
    }
    

提交回复
热议问题