我是新手編程,我試圖將一個數組傳遞給一個函數,並將所有元素添加到一起,並返回總和。問題是我得到了一筆垃圾值。我研究瞭如何將數組傳遞給函數,我不知道是否應該使用指針傳遞數組。反正我不擅長指針。試圖將一個數組傳遞給一個函數,並找到總和
這裏是我的代碼
#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