繁体   English   中英

在C中对任意函数1到10进行计数的函数

[英]Function that counts arbitrary function 1 to 10 in C

如何编写具有输入函数(对任何函数而言都是目标),输入数字数组和输入数组长度的函数?

功能:

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;
}

出什么问题了:

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会得到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;
}

两个想法:

  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]; 

就其价值而言,您的“累加器”功能在其他功能编程上下文中也被称为“减少” 如果您想使用Google这个词,那可能会有所帮助。

如果设置temp = array[0]并从i = 1而不是i = 0开始循环,则解决方案就差不多了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM