如果乘积为 0,它需要返回 NAN。目前它正在计算一些奇怪的值,我不太确定出了什么问题。
#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;
}
计算的值看起来是正确的,但当我进行手动计算时,值要大得多。 预先感谢您的帮助
最佳答案
您写道,如果乘积为 0,则必须返回 NAN
,但如果 product
为 1,则代码返回 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;
}
}
另请注意,使用 ==
运算符比较 double
是非常危险的。
关于c - 我正在用 C 创建一个数组,它计算数组的乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43154503/