本文介绍了计算双精度数组中所有元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用数组进行递归时有点困惑,有人可以纠正我的错误吗?
i am a bit confused in using array in doing recursion, can anyone correct my mistake?
新更新,根据需要提供的问题,某些行无法编辑
new update, based on question required some of the line cannot be edit
double sum_of_array(double x[],int size) { static double sum; <---can be edit int index = 0; <--can be edit if(index<size){ return sum + sum_of_array(x,size-1); <--can be edit } else { something ; <--can be edit return sum; <--can be edit } } int main(void){ double x[] = {4.5,5.0,6.8}; double y[] = {4.7,3.4,2.5,5.2}; cout<<"Sum X = "<<sum_of_array(x,3)<<endl; cout<<"Sum Y = "<<sum_of_array(y,4)<<endl; return 0; }输出:
Sum of the element in X[]=15.3 Sum of the element in Y[]= 15.8 推荐答案您从未真正将 x [] 和 y [] 中的值添加到 sum,此外, index 始终等于 0 .您可能应该将它作为另一个参数传递给函数:
You never actually add the values in x[] and y[] to sum and in addition, index is always equal to 0. You should probably pass it as another parameter to the function:
double sum_of_array(double x[], int size, int index) { if(index<size){ return x[index] + sum_of_array(x, size, index+1); } else { return 0; } }您实际上并不需要 sum 变量.
You don't actually need the sum variable.
更多推荐
计算双精度数组中所有元素的总和
发布评论