2013-02-25 70 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开始你的循环。