尝试将数组传递给函数并找到总和
Trying to pass an array to a function and find the sum
我是编程新手,我正在尝试将数组传递到函数中并将所有元素相加并返回总和。问题是我得到了总和的垃圾值。我已经研究了如何将数组传递给函数,但我不知道我是否应该使用指针来传递数组。反正我不擅长指针。
这是我的代码
#include <cmath>
#include <cstdlib>
using namespace std;
float mean(int);
int sum(int ARRZO[5]);
int total;
int main()
{
int ARRZ[5];
char *inname = "example.txt";
ifstream infile(inname);
if (!infile) {
cout << "There was a problem opening file " << inname << " for reading." << endl;
return 0;
}
cout << "Opened " << inname << " for reading." << endl;
for(int i=0; i<11; i++)
{
while (infile >> ARRZ[i])
{
cout << "Value from file is " << ARRZ[i] << endl;
}
}
total=sum(ARRZ);
cout<<"the sum of the elements in the array is"<<total<<endl;
system("PAUSE");
return 0;
}
int sum(int ARRZO[])
{
int sumz=0;
for (int i=0; i<5; i++)
{
sumz+=ARRZO[i];
cout<<ARRZO[i];
}
cout<<sumz<<endl;
return sumz;
}
由于
内部循环,您实际上是在ARRZ[0]
中读取文件中的所有值。当你到达i=1
时,你已经处于文件的末尾,并且没有阅读任何内容。
删除一个循环,并在成功读取值后递增i
。
我不确定你认为这对嵌套循环应该做什么:
for(int i=0; i<11; i++)
{
while (infile >> ARRZ[i])
{
cout << "Value from file is " << ARRZ[i] << endl;
}
}
但是(正如@aliexisdm指出的)内部循环读取文件的全部内容。他没有(至少直接)指出的是,你正在将这些值中的每一个都读入数组的第一个元素中。然后你回到外循环,递增i
,并尝试再次读取文件 - 但由于流的failbit
已经设置,你所有后续的读取尝试都保证会失败。
之后,您将数组中的 5 个项目相加,但由于您没有将任何内容读入其中的 4 个(并且从未初始化其内容),因此您最终会得到从文件中读取的最后一个项目 + 4 个垃圾值,结果给出了进一步的垃圾(好吧,通常无论如何 - 你真的有未定义的行为, 因此,该程序可能会崩溃并烧毁,但是对于大多数当前的计算机,您只会得到一些毫无意义的数字)。
但是,我建议更改程序,而不仅仅是删除一个循环并在剩余的循环中递增。相反,我会删除所有(显式)循环,并尝试真正利用标准库提供的内容。
您可以一举从文件中读取数字:
std::ifstream infile(inname);
std::vector<int> ARRZ ((std::istream_iterator<int>(infile)),
std::istream_iterator<int>());
然后你可以用std::accumulate
将它们全部求和:
int sum = std::accumulate(ARRZ.begin(), ARRZ.end(), 0);
最后,您可以打印出结果:
cout << "The sum of the elements in the array is: " << sum << "n";
但是,由于您仅从文件中读取值以将它们相加,因此您根本不需要存储它们。您可以将它们加在一起并打印出结果:
cout << "The sum of the elements in the file is: "
<< std::accumulate(std::istream_iterator<int>(infile),
std::istream_iterator<int>(), 0);
整个工作减少到一个台阶...
相关文章:
- 第 i 个元素返回 i 的函数数组
- 使用嵌套函数数组是个好主意吗?
- 正确实现类函数数组
- 试图引用已删除函数数组的相等运算符
- 如何在静态函数中使用成员函数数组
- 无法创建函数数组
- 构造函数数组
- 使用开关或定义函数数组 - 更快
- 编写一个函数,该函数将覆盖主函数数组中的值
- 可以像'funs[1]();'一样调用的函数数组
- std::AVX内部函数数组
- 如果数组大小未知,如何将函数数组作为参数传递
- 从函数数组中获取值
- 使用元编程在编译时初始化函数数组
- 将C函数数组转换为C++函数指针数组
- 复制构造函数 [数组] C++
- 添加函数数组并随机选择其中一个
- 指针到私有成员函数数组
- 可以单独声明函数数组的元素
- (c++)将main中的随机值保存到函数数组中