简体   繁体   中英

Why is the program printing 0s?

I've gone over the code and re-written it several times already and each time I get 0s when printing the array and the mean. I'm using codeblocks as the ide.

Below is statlib.c

// Calculates the mean of the array
double calculateMean(int totnum, double data[ ])
{
    double sum = 0.0;
    double average = 0.0;
    int i;

    // adds elements in the array one by one
    for(i = 0; i < totnum; i++ )
        sum += data[i];

    average = (sum/totnum);

return average;
}// end function calculateMean

Below is the other file

#include "statlib.c"
#include <stdio.h>

int main (void){

    int i; // counter used in printing unsorted array
    double mean = 0.0;
    double data[10] = {30.0,90.0,100.0,84.0,72.0,40.0,34.0,91.0,80.0,62.0};         // test data given in assignment
    int totnum = 10; // total numbers in array


//Print the unsorted array
printf("The unsorted array is: {");
    for ( i = 0; i < totnum; i++){
        printf(" %lf",data[i]);
        printf(",");
    }
    printf("}\n");

//Get and display the mean of the array
    mean = calculateMean(totnum,data);
    printf("The mean is: %lf\n",mean);

return 0;

}

You are trying to print mean with a %lf format specifier. That format specifier isn't valid , so probably something goes wrong there.

The correct format specifier for double would be %f , and the l length modifier is only allowed for integer formatting. (For floating point there is L , making %Lf the correct format specifier for long double ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM