c++ - (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;
}
解决方案
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.
推荐阅读
- c# - Nest在查询中将字段的第一个字母转换为小写
- c - 不打印c中的比较字符,双向链表
- python - 尝试在 django 中进行迁移/迁移时出错
- python - 如何安排python脚本
- android - 如何检测任何应用程序何时进入前台或在 android 中启动?
- python - 循环功能打印出多个相同的输出而不是一个
- c# - System.TypeInitializationException: 'CricApiConsoleDemo.ConsumeAPISync' 的类型初始化程序引发了异常。
- r - 我可以使用 read_excel 将 csv 文件导入 r 而不是使用 read.csv 吗?
- postgresql - 列出 PostgreSQL 版本 13 中的所有表、索引、视图、过程、物化视图
- php - 更新角度记录