C++ std::accumulate doesn't give the expected sum

前端 未结 5 1230
长发绾君心
长发绾君心 2020-12-05 13:18
double numbers[ ] = { 1, 0.5 ,0.333333 ,0.25 ,0.2, 0.166667, 0.142857, 0.125,
                       0.111111, 0.1 } ;
std::vector doublenumbers ( numb         


        
5条回答
  •  臣服心动
    2020-12-05 13:28

    std::accumulate will start to sum the type that is passed as 3rd argument, if you pass an integer, the return type will be int. And in this case implicitly converted to a double.

    In C++11 and C++14, if you want to prevent narrowing conversion, you could create an object using direct-list-initialization:

    double sum { std::accumulate(doublenumbers.begin(), doublenumbers.end(), 0) };
    

    The compiler will then give you a warning saying that you are trying to convert from int to double and also at which line. This will save you debugging time. And you can easily fix it so that it becomes correct:

    double sum { std::accumulate(doublenumbers.begin(), doublenumbers.end(), 0.0) };
    

提交回复
热议问题