【问题标题】:C# writing a function to calculate average age that takes array of objects as parameterC#编写一个函数来计算以对象数组为参数的平均年龄
【发布时间】:2021-03-17 13:53:36
【问题描述】:

我必须创建一个函数来计算一个班级 50 名学生的平均年龄,这是我的代码

        public class Student
        {
        public int[] age = new int[10];
        Student()
        {
            age[0] = 17;
            age[1] = 19;
            age[2] = 17;
            age[3] = 18;
            age[4] = 17;
            age[5] = 18;
            age[6] = 18;
            age[7] = 19;
            age[8] = 17;
            age[9] = 18;
        }

    }
    class Program
    {
        public void averageAge(Student student)
        {
            foreach(int i in student.age)
            {
                int avgage = (i += i) / 2;
            }
        }
        static void main (string[] args)
        {
          
        }

我得到一个错误,说不能分配给“i”它是一个 foreach 迭代变量,任何其他方式我都可以为学生年龄初始化这个数组,因为我必须计算 50 名学生的平均年龄,所以分配 50 个不同的时间感觉有点多余

我不知道以这种方式使用 foreach 时我在想什么,我现在用 for 循环交换了 foreach,如下所示:

public void averageAge(Student student)
        {
            int avgage = 0;
            for (int i =0;i<50;i++)
            {
               avgage += student.age[i];
            }
            avgage /= 50;
        }

【问题讨论】:

  • 你不能修改迭代变量。使用临时变量或 for 循环。
  • 只需在 foreach 之外创建一个变量并更新该 var 而不是“i”。
  • 您的问题的标题似乎与您的问题没有真正的关系。
  • 首先,你可以说int[] age = new int[] {10, 20, ... 50}; 列出所有值来初始化你的数组。请注意,您没有给出数组的大小,它最终会尽可能大。然后在循环之前初始化一个 int 变量var sum=0; 并在循环内执行此操作sum+=i;。然后在循环下方var average=sum/student.age.Length;。我不知道你期望int avgage = (i += i) / 2; 做什么。哦,是的,这与您的问题的标题有什么关系?另请注意,如果您想要 17.8 这样的结果,我的代码会进行整数除法(向下舍入),您需要进行强制转换
  • 您可以通过 List 启动并使用 linq var list = new List&lt;int&gt; { 1, 8, 3, 2 }; double result = list.Average();// result: 3.5 查找平均值

标签: c# arrays class integer average


【解决方案1】:

使用 Linq 你可以写:

using System.Linq;

var student = new Student();

int averageAge = (int)student.age.Average();

https://docs.microsoft.com/dotnet/api/system.linq.enumerable.average

否则你可以编写这个循环:

int averageAge = 0;

for ( int index = 0; index < student.age.Length; index++ )
  averageAge = ( averageAge + student.age[index] ) / 2;

Console.WriteLine(avgage);

一个foreach是:

foreach ( int value in student.age )
  averageAge = ( averageAge + value ) / 2;

因此方法可以是:

public int GetAverageAge(Student student)
{
  int result = 0;
    foreach ( int value in student.age )
      result = ( result + value ) / 2;
  return result;
}

你这样使用:

static void main (string[] args)
{
  var student = new Student();
  int averageAge = GetAverageAge(student);
}

输出:

Linq = 17
Loop = 17

将构造函数公开,您可以将方法放在类本身中:

public class Student
{
  public int[] age = new int[10];

  public int GetAverageAge()
  {
    int result = 0;
    foreach ( int value in student.age )
      averageAge = ( averageAge + value ) / 2;
    return result;
  }

  public Student()
  {
    ...
  }
}

你也可以使用属性:

public int AverageAge
{
  get
  {
    int result = 0;
    foreach ( int value in student.age )
      averageAge = ( averageAge + value ) / 2;
    return result;
  }
}

或者简单地说:

public int AverageAge => (int)age.Average();

每个班级的实例是针对一个学生的多个年龄还是一个学生班级?

【讨论】:

  • 它实际上是一个学生类,许多学生的年龄都在课堂上定义,不需要创建对象,只需将对象传递给计算数组平均年龄的函数数据字段(年龄)
  • 因此,您应该将类​​命名为Students,并在末尾加上s。例如,如果学生人数可能不同,您可能更喜欢使用 List&lt;int&gt; 表示年龄。也许您还可以考虑为每个学生和一组学生使用一个学生类。因此,Student 具有 AgeName... 并且具有字段 List&lt;Student&gt;Students 集合具有 AverageAge 属性并映射管理学生列表所需的所有内容。
  • 现在这有点太复杂了,最好有一个班级,即studentAges,并且该班级有一个数组数据字段ages,这是所有年龄段的集体数据字段学生,按照我的作业说明,将 studentsAges 类的对象作为参数传递给计算平均年龄的函数
【解决方案2】:

不是答案,但我认为这就是您想要实现的目标。它可能对您的思考过程有所帮助

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        // create a classroom
        var classRoom = new ClassRoom();
        // store 10 students in classroom, aged between 18 and 30 (random)
        for (int i = 0; i < 10; i++)
        {
            classRoom.Students.Add(new Student(new Random().Next(18, 30)));
        }

        // calculate average age of students in a classroom
        // this can be done a hundred ways. Linq is probably shortest
        Console.WriteLine($"There are {classRoom.Students.Count} students with an average age of { classRoom.Students.Average(s => s.Age)}");
        Console.ReadKey();
    }

    // a student has an age
    class Student
    {
        public Student(int age)
        {
            Age = age;
        }

        public int Age { get; set; }
    }

    // a class has a number of students
    class ClassRoom
    {
        public List<Student> Students { get; } = new List<Student>();
    }
}

【讨论】:

  • 这正是我想要的
  • 不客气。请注意,它与您的原始问题无关。甚至您的原始代码也没有。因此,您得到了反对票。对您的问题非常具体。
猜你喜欢
  • 1970-01-01
  • 2020-07-26
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2014-10-17
  • 1970-01-01
相关资源
最近更新 更多