このプログラムは、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