2013-02-25 69 views
0

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

回答

2

它不乘法工作,因爲通過0乘以任何東西給人,以及0

你需要使用第一個元素作爲初始值

double accumulator(double (*function)(double, double), double array[], int length) 
{ 
    int temp = array[0]; 
    for (int i = 1; i < length;i++) // start from #1 
    { 
     temp = (*function)(temp, array[i]); 

    } 
    return temp; 
} 
+0

是的,它的工作原理!:)我認爲這會讓我更加複雜,在開始時我很接近,而我錯過了一行:'int temp = array [0];':) – kelly 2013-02-25 17:21:47

4

什麼是錯的:

double multiplicator(double (*function)(double, double), double array[], int length) 
{ 
    int temp = 1; 
    for (int i = 0;i<length;i++) 
    { 
     temp = (*function)(temp, array[i]); 

    } 
    return temp; 
} 

Ë它具有不同的功能,或者您需要爲操作提供中性元素(總和爲0,產品爲1)。

+0

對於邊界情況(空數組),您總是需要提供一箇中性元素。 – fceller 2013-02-25 17:10:02

1

兩個想法:

  1. 你應該使用double temp而非int temp

  2. 您需要有一個不同的加法與乘法的起始值。總和應該從temp = 0開始,但產品應該從temp = 1開始。否則產品將始終爲0

    你可以添加添加一個初始值參數:

    double accumulator(double (*function)(double, double), double array[], int length, double initial) 
    

    或者你用第一個數組元素作爲起始值(但你需要檢查的其中數組是空的特殊情況):

    double temp = array[0]; 
    

對於它的價值,你的「蓄電池」功能或者稱爲"reduce"other福nctional編程上下文。如果你想Google這個詞,這可能會有所幫助。

1

您的解決方案几乎沒有,如果你設置temp = array[0]並從i = 1而不是i = 0開始你的循環。