我已經完成了代碼,並重新編寫了幾次,每次打印數組和平均值時都會得到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;
}
簡而言之,您的代碼看起來沒問題。我在http://codepad.org/xrWzazER上運行它,結果看起來如預期的那樣。 –
我也看不出太多錯誤。我期待通常的整數舍入等,但沒有... –
嘗試'%f'作爲格式說明符.. –