2017-04-01 1 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

당신은 당신이 제품은 0이지만 product 1.

지금 당신이 모든 시간 만 곱주의 경우 코드가 NAN를 반환하는 경우 NAN을 반환해야한다는 쓴 도움을 사전에 감사합니다 위치 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을 반환합니다. 제 최근 편집을 참조하십시오. –

관련 문제