首页 > 解决方案 > (C++) 我的函数不返回数组

问题描述

我是 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;
}

标签: c++arraysfunction

解决方案


You can use std::vector<int> instead of arrays. In C/C++ arrays decomposes into pointers while being passed in functions. Making things difficult.

Using std::vector<int> will take care of allocating and deleting and most importantly you can returns them from functions (copy construction) and no issues with temporary or what-so-ever.

Here is how to do it.

#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;
}

Actually you have a lot of mistakes in your code. Returning temporary and Index out of bound etcetra. Disable compiler extension and it will show you the warnings.


推荐阅读