为什么程序打印0?
我已经查看了代码并重新编写了几次,每次打印数组和均值时都得到0。 我正在使用代码块作为ide。
以下是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 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; }
您正尝试使用%lf
格式说明符打印mean
。 该格式说明符无效 ,因此可能出现问题。
double
的正确格式说明符为%f
, l
length修饰符仅允许整数格式化。 (对于浮点数,有L
,使得%Lf
为long double
的正确格式说明符)。