尝试将数组传递给函数并找到总和

Trying to pass an array to a function and find the sum

本文关键字:函数 数组      更新时间:2023-10-16

我是编程新手,我正在尝试将数组传递到函数中并将所有元素相加并返回总和。问题是我得到了总和的垃圾值。我已经研究了如何将数组传递给函数,但我不知道我是否应该使用指针来传递数组。反正我不擅长指针。

这是我的代码

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

整个工作减少到一个台阶...