mardi 1 mars 2016

C++ Auto Keyword - Float vs Int Trouble

I'm relatively new to C++. I just read about the auto keyword in regards to type deduction. I've tried implementing this in a couple functions only to find that it was causing all of kinds of issues when working with math operators. I believe what was happening was that my functions started implementing integer division when I actually needed float division (variables 'i' and 'avg'). I posted the code using the auto keywords below.

Now when I explicitly declared the variables as floats, the function worked fine.

So is this an example in which using auto would not be preferred? However, I can definitely see that they would help when generating the iterators.

namespace Probability
{
        /* ExpectedValueDataSet - Calculates the expected value of a data set */
        template <typename T, std::size_t N>
        double ExpectedValueDataSet(const std::array<T, N>& data)
        {
            auto i = 0;
            auto avg = 0;

            for(auto it = data.begin(); it != data.end(); it++)
            {
                i = it - data.begin() + 1;
                avg = ((i-1)/i)*avg + (*it)/i;
            }

            std::cout << avg << " \n";
            return avg;
        }

};

Aucun commentaire:

Enregistrer un commentaire