gpt4 book ai didi

c++ - 使用函数传递的最大元素初始化数组

转载 作者:行者123 更新时间:2023-11-30 01:27:23 25 4
gpt4 key购买 nike

我在学校工作,我应该编写一个函数来接受为公司工作的员 worker 数并将值返回给 main。

然后我将编写一个由 main 调用的函数,该函数接受为公司工作的员 worker 数。然后我应该询问每个员工在该职能中错过的天数,并返回错过的总天数。

我在第二部分遇到了问题。我正在尝试创建一个数组,其中员工数作为元素的最大数量,但我一直收到关于我放在括号之间的变量不是常量的错误,即使它是常量!

我对数组有点迷糊,这是一门进修类(class)。如果我可以创建一个数组,我会使用 for 循环遍历每个元素并存储每个元素中错过的天数。

感谢您的帮助,亚伦

#include <iostream>
using namespace std;

int noOfEmployees();
int daysAbsent(int);

int main(){
int employees;

employees = noOfEmployees();
daysAbsent(employees);

system("pause");
return 0;
}

int noOfEmployees(){
int employees;
cout<<"Please enter number of employees/n";
cin>>employees;
return employees;
}

int daysAbsent(int employees){
const int max = employees;
int daysMissed;
int workers [max];
}

最佳答案

[…] I keep getting an error about the variable I put in between the brackets not being a constant even though it is!

它必须是一个编译时常量;也就是说,编译器需要能够默默地替换 int workers [max]用类似 int workers [10] 的东西.在您的设计中,它取决于函数的参数,直到运行时才知道。

有几种不同的方法来处理这个问题,但最好的可能是使用 std::vector<int>而不是 int[] :

std::vector<int> workers;

(确保在程序的顶部是 #include <vector>)。

关于c++ - 使用函数传递的最大元素初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8992633/

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