2012-04-14 95 views
0

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

這裏是我的代碼

#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; 
} 
+0

你記得的#include''?我在格式化代碼時沒有看到它。 – Makoto 2012-04-14 01:00:25

+0

「總和垃圾值」?數組中的值怎麼樣?他們是垃圾嗎?如果你在數組中有垃圾,那麼當然,總和也是垃圾(古典GIGO原理)。 – AnT 2012-04-14 01:04:28

+6

另外,你似乎是**將11個值讀入大小爲5 **的數組(或者至少試圖這樣做)。爲什麼?該程序的行爲將是不確定的。只有這一點可以把任何東西變成垃圾 – AnT 2012-04-14 01:05:03

回答

1

我不知道你認爲這對嵌套的循環是應該做的:

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

整個工作減少到一步......

3

你實際上是在ARRZ[0]文件讀取,因爲內環的所有值。當你到達i=1時,你在文件末尾,而不是讀取任何東西。

刪除一個循環,並在成功讀取值後增加i

相關問題