该程序计算2x2矩阵中负元素的平均几何平均值,我试图理解下面这个程序中的代码以及作者为什么写他写的东西,有人可以向我解释下面这段代码的作用,我觉得很难理解什么作者在代码中写了太多指针
#include <stdio.h>
#include <math.h>
#define ROWS 2
#define COLS 2
char * last_geom_err = NULL;
float geometricMean(float * arr, int rows, int cols){
float neg_mul = 1;
int neg_count = 0;
float arr_elem;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if((arr_elem = *(arr + i * cols + j)) < 0){
neg_mul *= arr_elem;
neg_count++;
}
if (neg_count == 0){
last_geom_err = "no negative elements in array";
return 0;
}
if ((neg_count % 2 == 0) && (neg_mul < 0)){
last_geom_err = "a negative number under the square root of even degree";
return 0;
}
last_geom_err = NULL;
return pow(neg_mul, (float)neg_count);
}
int main(){
float arr[ROWS][COLS] = {
1., -2.,
-5., -6.
};
printf("Array:\n");
for(int i = 0; i < 2; i++){
for(int j = 0; j < 2; j++)
printf("%5.2f ", arr[i][j]);
putchar('\n');
}
float gm = geometricMean((float*)arr, ROWS, COLS);
if (last_geom_err != NULL)
printf("#Error of calculation: %s", last_geom_err);
else
printf("Geometric mean of negative elements of array = %5.2f", gm);
return 0;
}
为什么这个?
char * last_geom_err = NULL;
float geometricMean(float * arr, int rows, int cols){
float neg_mul = 1;
int neg_count = 0;
float arr_elem;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if((arr_elem = *(arr + i * cols + j)) < 0){
neg_mul *= arr_elem;
neg_count++;
}
if (neg_count == 0){
last_geom_err = "no negative elements in array";
return 0;
}
if ((neg_count % 2 == 0) && (neg_mul < 0)){
last_geom_err = "a negative number under the square root of even degree";
return 0;
}
last_geom_err = NULL;
return pow(neg_mul, (float)neg_count);
}
和这个
float gm = geometricMean((float*)arr, ROWS, COLS);
if (last_geom_err != NULL)
printf("#Error of calculation: %s", last_geom_err);
else
printf("Geometric mean of negative elements of array = %5.2f", gm);
return 0