如何编写一个具有输入函数(对任何函数都是客观的),输入数组数组和输入数组长度的函数?函数C中的任意函数1到10的计数
功能:
double accumulator(double (*function)(double, double), double array[], int length)
主要:
int main(){
double array[10];
for (int i=0; i<10; i++)
array[i] = i+1;
printf("Sum is: %g\n", accumulator(sum,array,10));
printf("Product is: %g\n", accumulator(product,array,10));
return 0;
}
例如总和应为55(1 + 2 + ... + 10)和产品362880(1 * 2 * .. * 10)。 我猜的功能由递归应该,但我仍然无法得到正确的结果:/
我有这个非递归解决方案,但它当然对仅适用于总和......
double accumulator(double (*function)(double, double), double array[], int length)
{
int temp = 0;
for (int i = 0;i<length;i++)
{
temp = (*function)(temp, array[i]);
}
return temp;
}
当然上面:
double sum(double x, double y){
return x+y;
}
double product(double x, double y){
return x*y;
}
是的,它的工作原理!:)我认为这会让我更加复杂,在开始时我很接近,而我错过了一行:'int temp = array [0];':) – kelly 2013-02-25 17:21:47