How to calculate the sum of squares of a vector of floating-point values in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <numeric> // accumulate

int main() {
    std::vector<double> arr = { 0.05, 0.86, 0.001, -0.29, -4.81 };

    double sumOfSquares = std::accumulate(
            arr.begin(), arr.end(), 0.0,
                [](double acc, double x) {
                        return acc + x * x;
                }
    );

    std::cout << sumOfSquares << std::endl;
}



/*
run:

23.9623

*/

 



answered Jun 29, 2025 by avibootz
...