제품이 0 인 경우 NAN을 반환해야합니다. 지금은 이상한 값을 계산하고 있으며, 무엇이 잘못되었는지는 확실하지 않습니다.배열의 제품을 계산하는 C 배열을 만듭니다.
#include <stdarg.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
#include <math.h>
double array_product(double arr[], int n) {
double product = 1;
for(int i = 0; i <= n; i++){
if(isfinite(arr[1]) == true){
product *= arr[1];
}
}
if(product == 1){
return NAN;
} else {
return product;
}
}
void call_function(const char * label, double x[], int count) {
double prod = array_product(x, count);
printf("%s\n", label);
printf("\tInput data:\n");
for (int i = 0; i < count; i++) {
printf("\t%d\t%f\n", i, x[i]);
}
printf("\tProduct = %f\n\n", prod);
}
int main(void) {
double x1[] = {0};
call_function("Count == 0", x1, 0);
double x2[] = { NAN, +INFINITY, -INFINITY };
call_function("No finite values", x2, 3);
double x3[] = { 1, 2, 3, 4, 5, 6, 7 };
call_function("Several finite values", x3, 7);
double x4[] = { 2, M_PI, NAN, 3, INFINITY, 4 };
call_function("A mix of finite values and infinities", x4, 6);
return 0;
}
계산 된 값은 정확하지만 수동 계산을 수행하면 값이 훨씬 커집니다. 는
함수가'array_product()'안의'arr [1]'에서 인덱스가 항상'1' 인 이유를 알지 못합니다. 당신은 모든 요소들을 반복하고 그것들을 곱하려고하지 않습니까? – babon