Algorithms

근삿값 알고리즘

Korokke 2022. 9. 1. 16:19

 

        public static void Main(string[] args)
        {
            int min = int.MaxValue;

            int[] numbers = { 10, 20, 30, 29, 17 };

            // target의 근삿값을 찾을 것
            int target = 11;

            // target에 가장 가까운 값을 넣을 변수
            int near = 0;

            for (int i = 0; i < numbers.Length; i++)
            {
                if(min > Math.Abs(numbers[i] - target))
                {
                    min = Math.Abs(numbers[i] - target);
                    near = numbers[i];
                }
            }
            Console.WriteLine(near);
        }

결과값

 

 

 

참조: https://www.youtube.com/watch?v=GyT1WDWswGA&list=PLO56HZSjrPTD8FIsr5tIO_foTN_kmXLEM&index=7