Calculate median in c#

前端 未结 12 1496
别跟我提以往
别跟我提以往 2020-11-29 23:35

I need to write function that will accept array of decimals and it will find the median.

Is there a function in the .net Math library?

12条回答
  •  青春惊慌失措
    2020-11-30 00:07

    Sometime in the future. This is I think as simple as it can get.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Median
    {
        class Program
        {
            static void Main(string[] args)
            {
                var mediaValue = 0.0;
                var items = new[] { 1, 2, 3, 4,5 };
                var getLengthItems = items.Length;
                Array.Sort(items);
                if (getLengthItems % 2 == 0)
                {
                    var firstValue = items[(items.Length / 2) - 1];
                    var secondValue = items[(items.Length / 2)];
                    mediaValue = (firstValue + secondValue) / 2.0;
                }
                if (getLengthItems % 2 == 1)
                {
                    mediaValue = items[(items.Length / 2)];
                }
                Console.WriteLine(mediaValue);
                Console.WriteLine("Enter to Exit!");
                Console.ReadKey();
            }
        }
    }
    

提交回复
热议问题