c++ - 类递归数组

标签 c++ arrays function class recursion

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

#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;
    // ...
}

否则,就像其他答案所说的那样,在您的原始代码中您忘记了重置索引(这正是将它存储在类中很奇怪的原因)。

关于c++ - 类递归数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47526749/

相关文章:

c++ - 内存分配责任

java - 当索引未知时如何更改数组中的一个位置?

c++ - 创建一个比较函数来对 C 风格的字符串进行排序

python - 我的方法在我自己的程序中得到认可。可能是新手错误

C++,传递给函数的fstream对象作为引用,const?

c++ - 在 C++ 中将字符串写入文件的首选方法是什么,使用 '+' 或几个 '<<' ?

c++ - 如何在Qt中制作exe文件?

c++ - const 类对象与 const 数据成员有何不同?

arrays - PostgreSQL 数组(row_to_json()) : How to stop array() functions from adding "quotes to strings and escape\existing " quotes

Javascript 函数未在 document.ready jquery 代码中定义