Animals.Animal.AverageAge C# (CSharp) Метод

AverageAge() публичный статический Метод

public static AverageAge ( List animalList ) : int
animalList List
Результат int
        public static int AverageAge(List<Animal> animalList)
        {
            int sum = 0;
            for (int i = 0; i < animalList.Count; i++)
            {
                sum += animalList[i].Age;
            }
            return sum / animalList.Count;
        }
    }

Usage Example

Пример #1
0
        static void Main()
        {
            Dog dogNinja = new Dog("Stamat", 6, Sex.Male);

            dogNinja.Sound();

            Kitten kotence = new Kitten("Eli", 1, Sex.Female);

            // This will throw exeption
            // Kitten kotence = new Kitten("Eli", 1, Sex.Male);

            List <Animal> animalList = new List <Animal>();

            animalList.Add(new Frog("Stamat", 2, Sex.Male));
            animalList.Add(new Tomcat("Stamat", 1, Sex.Male));
            animalList.Add(new Dog("Stamat", 3, Sex.Male));
            animalList.Add(new Kitten("Stamat", 5, Sex.Female));
            animalList.Add(new Frog("Stamat", 7, Sex.Male));
            animalList.Add(new Tomcat("Stamat", 12, Sex.Male));
            animalList.Add(new Dog("Stamat", 65, Sex.Male));
            animalList.Add(new Kitten("Stamat", 47, Sex.Female));
            animalList.Add(new Frog("Stamat", 12, Sex.Male));
            animalList.Add(new Tomcat("Stamat", 36, Sex.Male));
            animalList.Add(new Dog("Stamat", 48, Sex.Male));
            animalList.Add(new Kitten("Stamat", 16, Sex.Female));
            animalList.Add(new Frog("Stamat", 42, Sex.Male));
            animalList.Add(new Tomcat("Stamat", 36, Sex.Male));
            animalList.Add(new Dog("Stamat", 71, Sex.Male));
            animalList.Add(new Kitten("Stamat", 30, Sex.Female));

            int averageAge = Animal.AverageAge(animalList);

            Console.WriteLine("The average age of all animals is: {0}", averageAge);
        }