2017-04-01 69 views
0

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

计算的值看起来是正确的,但是当我做手动计算的时候这些值要大得多。 预先感谢您的帮助

+1

我不明白为什么索引在函数array_product()内的'arr [1]'中总是'1'。你不是想循环所有的元素,并把它们相乘吗? – babon

回答

1

你写,你必须返回NAN如果产品是0,但你的代码返回NAN如果product为1

现付,你只乘以所有的时间关注位置1和循环中的元素应迭代至n但不包括。

double array_product(double arr[], int n) { 
    double product = 1.0; 
    bool multPerformed = false; 

    for(int i = 0; i < n; i++){ 
     if(isfinite(arr[i])){ 
      product *= arr[i]; 
      multPerformed = true; 
     } 
    } 

    if(product == 0.0 || !multPerformed){ 
     return NAN; 
    } else { 
     return product; 
    } 
} 

还要注意的是使用== oprator比较double是非常危险的。

+0

@ BobFisher3请参阅我的编辑代码 –

+0

必须将if(n == 0 || product == 0.0)更改为== 1.0,现在它可以工作!感谢您的帮助:) – BobFisher3

+0

@ BobFisher3但如果您的输入数组是{1.0,1.0,1.0},它将返回NAN。请看我最近的编辑。 –