Nice programing

가장 가까운 5로 반올림

nicepro 2020. 11. 19. 22:02
반응형

가장 가까운 5로 반올림


2 배를 가장 가까운 5로 반올림해야합니다. Math.Round 함수로 수행하는 방법을 찾을 수 없습니다. 어떻게 할 수 있습니까?

내가 원하는 것 :

70 = 70
73.5 = 75
72 = 70
75.9 = 75
69 = 70

등등..

이 작업을 수행하는 쉬운 방법이 있습니까?


시험:

Math.Round(value / 5.0) * 5;

이것은 작동합니다 :

5* (int)Math.Round(p / 5.0)

다음은 코드를 확인할 수있는 간단한 프로그램입니다. MidpointRounding 매개 변수가 없으면 가장 가까운 짝수로 반올림됩니다. 이는 귀하의 경우 5의 차이를 의미합니다 (72.5 예제에서).

    class Program
    {
        public static void RoundToFive()
        {
            Console.WriteLine(R(71));
            Console.WriteLine(R(72.5));  //70 or 75?  depends on midpoint rounding
            Console.WriteLine(R(73.5));
            Console.WriteLine(R(75));
        }

        public static double R(double x)
        {
            return Math.Round(x/5, MidpointRounding.AwayFromZero)*5;
        }

        static void Main(string[] args)
        {
            RoundToFive();
        }
    }

참고 URL : https://stackoverflow.com/questions/1531695/round-to-nearest-five

반응형