data type is double, but below decimal point is calculated 0

78 Views Asked by At

Code explain: When I input three number, each number is saved in list[]. And then, it prints average and standard deviation.

Problem: standard_deviation value's below decimal point is calculated 0. I would really appreciate it if you tell me where I am wrong.


#include <stdio.h>
#include <math.h>
#define SIZE 3

int get_average(int a[], int size);
int get_standard_deviation(int a[], int size, double average); 

int main(void) {
    int list[SIZE]; 
    int i; 
    double average, standard_deviation;

    for (i = 0; i < SIZE; i++) {
        printf("input data:");
        scanf("%d", &list[i]); 
    }
    average = get_average(list, SIZE); 
    standard_deviation = get_standard_deviation(list, SIZE, average);

    printf("average is %lf.\n", average);  
    printf("standard deviation is %lf.\n", standard_deviation); 
     
    return 0;
}
int get_average(int a[], int size) { 
    int i;
    int sum = 0;
    double result;
    for (i = 0; i < size; i++) {
        sum += a[i];
    }
    result = (double)sum / size;
    return result;
}
int get_standard_deviation(int a[], int size, double average) {    
    double result;
    int i;
    double sum = 0;
    for (i = 0; i < size; i++) {
        sum += (a[i] - average) * (a[i] - average); 
    }
    result = (double)sqrt(((double)sum / size)); 
    return result; 
}

I tried to change the data types of variables to double type. My expectation is that 'standard_deviation' demical point value is also calculated.

1

There are 1 best solutions below

0
Aram Grigoryan On

First of the firsts, you need to change return type for get_standard_deviation() function, since now there is double to int cast, which will cause that you are getting the integer part of number.

Your function need to be like this double get_standard_deviation(int a[], int size, double average)