Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to calculate the mean and the standard deviation of a vector of floating-point values in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <cmath> // sqrt
#include <iomanip> // setprecision

double CalculateMean(const std::vector<double>& data) {
    if (data.empty()) {
        return 0.0;
    }

    double sum = 0.0;
    for (double value : data) {
        sum += value;
    }
    
    return sum / data.size();
}

double CalculateStandardDeviation(const std::vector<double>& data, double mean) {
    size_t n = data.size();
    if (n < 2) {
        return 0.0;
    }

    double sumOfSquaredDifferences = 0.0;
    for (double value : data) {
        double diff = value - mean;
        sumOfSquaredDifferences += diff * diff;
    }

    double variance = sumOfSquaredDifferences / (n - 1);
    
    return std::sqrt(variance);
}

int main() {
    std::vector<double> numbers = {3.4, 1.8, 4.3, 5.0, 6.2};

    double mean = CalculateMean(numbers);
    double stddev = CalculateStandardDeviation(numbers, mean);

    std::cout << std::fixed << std::setprecision(2);
    std::cout << "Mean: " << mean << std::endl;
    std::cout << "Standard Deviation: " << stddev << std::endl;
}



/*
run:

Mean: 4.14
Standard Deviation: 1.66

*/

 



answered Jun 29, 2025 by avibootz
...