如何編寫一個具有輸入函數(對任何函數都是客觀的),輸入數組數組和輸入數組長度的函數?函數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