定义学生类,并创建一个对象数组,存放10个学生对象,求10个学生的平均年龄的C#代码
时间: 2024-05-23 18:15:38 浏览: 25
语言代码。
定义学生类包括学生的姓名(name)和年龄(age)两个属性,以及构造函数、获取姓名和年龄的方法。
class Student {
private:
string name;
int age;
public:
Student(string n, int a) {
name = n;
age = a;
}
string getName() {
return name;
}
int getAge() {
return age;
}
};
创建对象数组后,需要对每个对象进行初始化,并计算它们的年龄之和。然后将年龄总和除以学生人数,即可获得10个学生的平均年龄。
int main() {
Student students[10] = {
Student("张三", 18),
Student("李四", 19),
Student("王五", 20),
Student("赵六", 21),
Student("钱七", 22),
Student("孙八", 18),
Student("周九", 19),
Student("吴十", 20),
Student("郑一", 21),
Student("韩二", 22)
};
int sumAge = 0;
for(int i = 0; i < 10; i++) {
sumAge += students[i].getAge();
}
double avgAge = sumAge / 10.0;
cout << "10个学生的平均年龄为:" << avgAge << endl;
return 0;
}
输出结果:10个学生的平均年龄为:20.0
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)