2014-09-22 184 views
-3

我正在使用for loop來獲取txt文件中的值。查找數組中值的平均值

我想將數字平均在一起。所以我這樣做,

int size = 0; 
double sum = 0; 


for (int i = 0; i < size; ++i) 
{ 
    sum += data[i].getQuantity(); 
} 
double avg = ((double)sum)/size; //or cast sum to double before division 

std::cout << avg << '\n'; 

return 0; 

當我cout平均我得到80nan。我認爲我需要做atod但我似乎無法正確實施此。

缺少什麼我在這裏找到存儲在內部getQuantity

#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <string> 
#include <vector> 
#include <iterator> 

struct Input 
{ 
    friend std::istream& operator >>(std::istream& inp, Input& item); 
    friend std::ostream& operator <<(std::ostream& outp, Input const& item); 

    std::string group; 
    float total_pay; 
    unsigned int quantity; 

    Input() : group(), total_pay(), quantity() 
    { 
    } 

    Input(std::string groupIn, float total_payIn, unsigned int quantityIn) : 
    group(std::move(groupIn)), 
    total_pay(total_payIn), 
    quantity(quantityIn) 
    { 
    } 

    std::string const& getGroup() const { return group; } 
    float getTotalPay() const { return total_pay; } 
    unsigned int getQuantity() const { return quantity; } 
}; 

std::istream& operator >>(std::istream& inp, Input& item) 
{ 
    return (inp >> item.group >> item.total_pay >> item.quantity); 
} 

std::ostream& operator <<(std::ostream& outp, Input const& item) 
{ 
    outp 
    << item.getGroup() << ' ' 
    << item.getTotalPay() << ' ' 
    << item.getQuantity(); 
    return outp; 
} 


int main() 
{ 
    std::ifstream infile("input.txt"); 
    if (!infile) 
    { 
     std::cerr << "Failed to open input file" << '\n'; 
     exit(EXIT_FAILURE); 
    } 

    std::vector<Input> data; 
    std::string line; 
    while (std::getline(infile, line)) 
    { 
     std::istringstream iss(line); 
     Input inp; 
     if (iss >> inp) // calls our extaction operator >> 
      data.push_back(inp); 
     else 
      std::cerr << "Invalid input line: " << line << '\n'; 
    } 

    std::copy(data.begin(), data.end(), 
       std::ostream_iterator<Input>(std::cout,"\n")); 

    std::cout << data[2].getQuantity(); 


    int size = 0; 
    double sum = 0; 


    for (int i = 0; i < size; ++i) 
    { 
     sum += data[i].getQuantity(); 
    } 
    double avg = ((double)sum)/size; 

    std::cout << avg << '\n'; 

    return 0; 
} 
+2

請發佈[MCVE](http://stackoverflow.com/help/mcve)。您發佈的代碼中'size'爲'0'。這不會很好。 – juanchopanza 2014-09-22 22:16:58

+0

文件的閱讀位置和getQuantity的定義是什麼? – Christophe 2014-09-22 22:18:08

+0

我添加了我的代碼。好的,我改變大小的值,看看是否有效。但是,每次循環時不應該加1來確定大小? – wuno 2014-09-22 22:21:07

回答

1

變化

int size = 0; 

size_t size = data.size(); 

所以,你設置正確的值size,次循環正確的號碼,然後通過正確的號碼,而不是0劃分。

+0

,對我來說這很讓人驚訝,三個人會花時間去投票給我。感謝您的幫助。 – wuno 2014-09-23 21:01:05

1

您是通過0將在這個程序中的平均數值,這總是會導致ERROR
的計劃,因爲除以0根本不可能。