找到数组中值的平均值

时间:2014-09-22 22:15:51

标签: c++

我使用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;

当我提高平均值时,我得到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 个答案:

答案 0 :(得分:1)

您在此计划中除以0,这将始终产生ERROR
在一个程序中,因为除以0根本不可能。

答案 1 :(得分:1)

更改

int size = 0;

size_t size = data.size();

因此,您将正确的值设置为size,循环正确的次数,然后除以正确的数字而不是0