如果产品为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