类递归数组

Class Recursive Array

本文关键字:数组 递归      更新时间:2023-10-16

我的问题是,我不明白为什么我无法获得数组随机数的所需总和。有人可以帮我找出错误吗?

#include <iostream>
using namespace std;
class Recursion{
   int max_size;
   double sum;
   int index;
   double* arr;
public:
   Recursion(int);
   void fill_array();
   void sum_array();
};
Recursion::Recursion(int size){//from main
   max_size = size;
   sum = 0;
   index = 0;
   arr = new double[max_size];
}
void Recursion::fill_array(){
   if (index == max_size){
      cout << "Array is Full." << endl;
      //stop array
   }
   else{
      arr[index] = rand() % 10+1;
      cout << arr[index] << endl;
      index++; 
      fill_array();
   }
}
void Recursion::sum_array(){
   if (index == max_size){
      cout << "Sum is: "<< sum << "!"<< endl;
   }
   else{
      sum = sum + arr[index];
      index++;
      sum_array();
   }
}
int main(){
   Recursion connect(5);
   connect.fill_array();
   connect.sum_array();
   return 0;
}

输出为:

8
10
4
9
1
Array is Full.
Sum is: 0!

使用对象字段进行递归是最不寻常的。.index之类的变量通常以参数的形式传递:

double Recursion::sum_array(int index) {
    if (index >= max_size) {
        return 0;
    } else {
        return arr[index] + sum_array(index + 1);
    }
}
int main() {
    // ...
    cout << "Sum is: "<< sum_array(0) << "!"<< endl;
    // ...
}

否则,就像其他答案所说的那样,在您的原始代码中,您忘了重置索引(这就是为什么将其存储在班级中很奇怪)。

此调用后:

connect.fill_array();

index等于max_size。当您完成填充数组时(以其他功能可用)时,您需要将其重新定位为0,例如:

   if (index == max_size){
      cout << "Array is Full." << endl;
      index =0;
      //stop array
   }

现在输出为:

4
7
8
6
4
Array is Full.
Sum is: 29!

个人意见:

将索引作为类的数据模因,以在两个函数之间共享,但不需要共享(我的意思是不是一个人在另一个中间步骤中使用当前值)奇怪的,并且可能像您已经经历的那样导致错误。

索引,即在数组上循环的计数器应局部分配到当时循环数组的函数,因此我建议将index从您的班级,数据成员中丢弃,并将其作为一个将其传递给功能中的参数。此外,您可以为该参数增添默认值,因为您想从数组的开头循环。

将所有东西放在一起,我们得到:

#include <iostream>
using namespace std;
class Recursion{
   int max_size;
   double sum;
   double* arr;
public:
   Recursion(int);
   void fill_array(int index);
   void sum_array(int index);
};
Recursion::Recursion(int size){//from main
   max_size = size;
   sum = 0;
   arr = new double[max_size];
}
void Recursion::fill_array(int index = 0){
   if (index == max_size){
      cout << "Array is Full." << endl;
      //stop array
   }
   else{
      arr[index] = rand() % 10+1;
      cout << arr[index] << endl;
      index++; 
      fill_array(index);
   }
}
void Recursion::sum_array(int index = 0){
   if (index == max_size){
      cout << "Sum is: "<< sum << "!"<< endl;
   }
   else{
      sum = sum + arr[index];
      index++;
      sum_array(index);
   }
}
int main(){
   Recursion connect(5);
   connect.fill_array();
   connect.sum_array();
   return 0;
}

最终打印中的!让我有些吓到了,您可能需要将其删除(例如,用点替换),因为它可能会使用户混淆,并将其与castorials混淆。

呼叫sum_array索引等于max_size时,您应该在fill_array方法中清除它。

void Recursion::fill_array(){
if (index == max_size){
  cout << "Array is Full." << endl;
  //stop array
  index = 0;
}

fill_array()索引之后设置为max_size。您必须将索引重置为0,然后拨打sum_array()