利用windows窗体实现:创建一个学生类(包含姓名、学号、年龄),并创建一个对象数组,存放5个学生对象,求5个学生的平均年龄并输出。
时间: 2023-12-10 20:42:53 浏览: 49
以下是用 C# 的 Windows 窗体实现的代码:
```csharp
using System;
using System.Windows.Forms;
namespace StudentAverageAge
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
Student[] students = new Student[5];
students[0] = new Student("张三", "1001", 20);
students[1] = new Student("李四", "1002", 21);
students[2] = new Student("王五", "1003", 19);
students[3] = new Student("赵六", "1004", 22);
students[4] = new Student("钱七", "1005", 20);
int sum = 0;
foreach (Student student in students)
{
sum += student.Age;
}
double averageAge = (double)sum / students.Length;
lblResult.Text = "5个学生的平均年龄为:" + averageAge.ToString("F2");
}
}
public class Student
{
public string Name { get; set; }
public string ID { get; set; }
public int Age { get; set; }
public Student(string name, string id, int age)
{
Name = name;
ID = id;
Age = age;
}
}
}
```
在窗体上添加一个按钮和一个标签,将按钮的 `Click` 事件绑定到 `btnCalculate_Click` 方法上,然后在该方法中创建 5 个学生对象,计算平均年龄并显示在标签上。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)