我是新手编程,我试图将一个数组传递给一个函数,并将所有元素添加到一起,并返回总和。问题是我得到了一笔垃圾值。我研究了如何将数组传递给函数,我不知道是否应该使用指针传递数组。反正我不擅长指针。试图将一个数组传递给一个函数,并找到总和
这里是我的代码
#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;
}
你记得的#include''?我在格式化代码时没有看到它。 –
Makoto
2012-04-14 01:00:25
“总和垃圾值”?数组中的值怎么样?他们是垃圾吗?如果你在数组中有垃圾,那么当然,总和也是垃圾(古典GIGO原理)。 – AnT 2012-04-14 01:04:28
另外,你似乎是**将11个值读入大小为5 **的数组(或者至少试图这样做)。为什么?该程序的行为将是不确定的。只有这一点可以把任何东西变成垃圾 – AnT 2012-04-14 01:05:03