gpt4 book ai didi

c++ - 我的代码中列表、成员函数和类的使用是否正确?

转载 作者:行者123 更新时间:2023-11-30 04:52:03 25 4
gpt4 key购买 nike

在用 MATLAB 编码后,我不得不回到 C++。我缺少一些东西。不管怎样,我写了一个代码来创建可扩展的人名、姓氏和年龄列表。我所说的可扩展是指,如果需要,以后可以添加更多条目。

它实例化了 5 个人的名字、姓氏和年龄。我需要使其可扩展,并计算人员列表的平均年龄。我在我的代码中使用了列表。

#include <iostream>
#include <list>

int main() {
// Create a list of first names and initialize it with 5 first names
std::list<string> firstname(new string[] { "Brad", "John", "Neptune", "Kuh", "Dhar", "Rock" });

// Iterate over and display first names
for (string val : firstname)
std::cout << val << ",";
std::cout << std::endl;

// Create a list of last names and initialize it with 5 last names
std::list<string> lastname(new string[] { "Mish", "Jims", "Nepers", "Yho", "Har", "Ock" });

// Iterate over and display first names
for (string val2 : lastname)
std::cout << val2 << ",";
std::cout << std::endl;


// Create an empty list of ages pf persons
std::list<int> ages(5, {34, 56, 57, 91, 12});

// Iterate over the list and display ages
for (int val1 : ages)
std::cout << val1 << ",";
std::cout << std::endl;

// Compute average age
for (int jj=0; jj <5; jj++)
agesum = age(jj) + age(jj+1);
avage = agesum/(jj+1);
return 0;
}

但是它不执行,并给出错误。您能否更正代码,并就发生的情况向我提供反馈?

最佳答案

这是你想要的吗?

#include <string>
#include <iostream>
#include <vector>

int main(){

std::vector<std::string> first_names {"Brad", "John", "Neptune", "Kuh", "Dhar", "Rock"};
std::vector<std::string> last_names {"Mish", "Jims", "Nepers", "Yho", "Har", "Ock"};
std::vector<int> ages {34, 56, 57, 91, 12};

int avg_age = 0;

for(int age : ages) avg_age += age;
avg_age /= ages.size();


if(first_names.size() == last_names.size()){
for(int i = 0; i < first_names.size(); i++){

std::cout << first_names[i] << " " << last_names[i] << "\n";

}
}
std::cout << "average age: " << avg_age << "\n";
}

关于c++ - 我的代码中列表、成员函数和类的使用是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54642052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com