如何编写具有输入功能(对任何功能都是客观的),输入数组和输入数组长度的函数?
功能:
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;
}
答案 0 :(得分: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表示产品)。
答案 1 :(得分: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;
}
答案 2 :(得分:1)
两个想法:
您应该使用double temp
而不是int temp
。
您需要为加法与乘法设置不同的起始值。总和应从temp = 0
开始,但产品应从temp = 1
开始。否则产品将始终为0。
您可以添加另一个初始值参数:
double accumulator(double (*function)(double, double), double array[], int length, double initial)
或者您使用第一个数组元素作为起始值(但是您需要检查数组为空的特殊情况):
double temp = array[0];
对于它的价值,你的“累加器”函数在"reduce"函数式编程上下文中也称为other。如果您想要Google这个术语,这可能会有所帮助。
答案 3 :(得分:1)
如果您设置temp = array[0]
并在i = 1
而不是i = 0
开始循环,那么您的解决方案几乎就在那里。