计算双精度数组中所有元素的总和

编程入门 行业动态 更新时间:2024-10-19 11:54:24
本文介绍了计算双精度数组中所有元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在使用数组进行递归时有点困惑,有人可以纠正我的错误吗?

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.

更多推荐

计算双精度数组中所有元素的总和

本文发布于:2023-10-24 20:01:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524865.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   精度   组中   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!