2015-10-16 136 views
0

我已經完成了代碼,並重新編寫了幾次,每次打印數組和平均值時都會得到0。我使用代碼塊作爲ide。爲什麼程序打印0?

下面是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 

下面是其他文件

#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; 

} 
+2

簡而言之,您的代碼看起來沒問題。我在http://codepad.org/xrWzazER上運行它,結果看起來如預期的那樣。 –

+0

我也看不出太多錯誤。我期待通常的整數舍入等,但沒有... –

+4

嘗試'%f'作爲格式說明符.. –

回答

2

你要打印mean%lf格式說明。該格式說明符isn't valid,所以可能出現問題。

double的正確格式說明符應該是%f,並且l長度修飾符只能用於整數格式。 (對於浮點,有L,因此%Lflong double的正確格式說明符)。

+0

OP說「代碼塊」,但沒有指定使用什麼*編譯器*。鐺,例如,將輸出警告與這種結構。 – usr2564301

+0

@Jongware我認爲編譯器是GNU GCC – Vanessa