gpt4 book ai didi

c++ - 计算 double 组中所有元素的总和

转载 作者:太空狗 更新时间:2023-10-29 23:33:56 27 4
gpt4 key购买 nike

我在使用数组进行递归时有点困惑,谁能纠正我的错误?

新的更新,根据需要的问题某些行无法编辑

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

最佳答案

您正试图制作一些过度设计的东西。您需要两件事 - 边缘情况(递归截止)和一般情况(递归下降)。在您的情况下,边缘情况是“数组大小为零”,一般情况是“获取第一个元素并将数组的其余部分传递给递归”。

可能是这样的:

double sum_of_array( double x[], int size )
{
if( size == 0 ) { //this is the edge case
return 0;
}

// here you grab the first element and pass the rest of array into a recursive call
return x[0] + sum_of_array( x + 1, size - 1 );
}

关于c++ - 计算 double 组中所有元素的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7495492/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com