(C++)我的函数不返回数组
(C++) My Function Does Not Return Array
我是 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;
}
实际上,您的代码中有很多错误。临时返回和索引出界等。禁用编译器扩展,它将显示警告。
相关文章:
- 从 C++ 中的函数返回数组地址问题
- 如何在 c++ 函数中返回数组
- 如何从 c++ 中的函数返回数组
- 为什么 c++ 函数可以正确返回数组的大小?
- 解释通过从函数引用返回数组的语法
- (C++)我的函数不返回数组
- 如何按 C++ 中的值从函数返回数组
- 返回数组中值的指针地址
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 使用数组类返回数组c++
- 如何使函数返回数组?用于制作在VB.NET中使用的DLL
- 从函数 BY VALUE 返回数组,返回结构时会发生什么?
- 调用和打印函数,在 C++ 中返回数组
- 如何使用递归函数返回数组中整数的索引?
- 从函数返回数组时是否需要删除
- 为什么从函数返回数组时需要将数组声明为静态数组.(C++)
- C++返回数组而不进行动态内存分配?
- 在函数 c++ 中返回数组时出现问题
- 如何从C 中的函数返回数组
- 如何使类函数返回数组,然后将其调用并存储在 main 中