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 an array of floating-point values in C

1 Answer

0 votes
#include <stdio.h>
#include <math.h>

double CalculateMean(const double data[], int size) {
    if (size == 0) return 0.0;

    double sum = 0.0;
    for (int i = 0; i < size; i++) {
        sum += data[i];
    }
    return sum / size;
}

double CalculateStandardDeviation(const double data[], int size, double mean) {
    if (size < 2) return 0.0;

    double sumOfSquaredDifferences = 0.0;
    for (int i = 0; i < size; i++) {
        double diff = data[i] - mean;
        sumOfSquaredDifferences += diff * diff;
    }

    double variance = sumOfSquaredDifferences / (size - 1); // sample standard deviation
    return sqrt(variance);
}

int main() {
    double numbers[] = {3.4, 1.8, 4.3, 5.0, 6.2};
    int size = sizeof(numbers) / sizeof(numbers[0]);

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

    printf("Mean: %.2f\n", mean);
    printf("Standard Deviation: %.2f\n", stddev);

    return 0;
}



/*
run:

Mean: 4.14
Standard Deviation: 1.66

*/

 



answered Jun 29, 2025 by avibootz
...