(C++)我的函数不返回数组

(C++) My Function Does Not Return Array

本文关键字:返回 数组 函数 我的 C++      更新时间:2023-10-16

我是 c++ 编程的新手。在下面的代码中,我希望用户输入每个员工的员工人数和销售额。然后程序将为每位员工写入相应的销售额。虽然编译器没有给出错误,但它不起作用。你能帮我找到错误在哪里吗?提前谢谢。

#include <iostream>
using namespace std;
int enterSales(int max){
int sales[max];
for (int idx=0;idx<max;idx++){
cout<<"Enter the amount of sales for person #"<<idx<<": ";
cin>>sales[idx];
}
return sales[max];
}
float showSalesComm(int max){
int sales[]={enterSales(max)};
for (int idx=0;idx<max;idx++){
cout<<"The amount of sales for person #"<<idx<<": ";
cout<<sales[idx]<<endl;
}
return 0;
}
int main () {
int max;
cout<<"Enter the number of employees.";
cin>>max;
showSalesComm(max); 
return 0;
}

您可以使用std::vector<int>而不是数组。在 C/C++ 中,数组在传入函数时分解为指针。让事情变得困难。

使用std::vector<int>将负责分配和删除,最重要的是,您可以从函数(复制构造(中返回它们,并且没有临时或类似问题。

这是如何做到的。

#include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::cin;
using std::endl;
vector<int> enterSales(int max){
int temp;
vector<int> a;
for (int idx=0;idx<max;idx++){
cout<<"Enter the amount of sales for person #"<<idx<<": ";
cin>>temp;
a.push_back(temp);
}
return a;
}
void showSalesComm(int max){
vector<int> sales=enterSales(max);
for (int idx=0;idx<max;idx++){
cout<<"The amount of sales for person #"<<idx<<": ";
cout<<sales[idx]<<endl;
}
}
int main () {
int max;
cout<<"Enter the number of employees.";
cin>>max;
showSalesComm(max); 
return 0;
}

实际上,您的代码中有很多错误。临时返回和索引出界等。禁用编译器扩展,它将显示警告。