类递归数组
Class Recursive Array
我的问题是,我不明白为什么我无法获得数组随机数的所需总和。有人可以帮我找出错误吗?
#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()
相关文章:
- 使用递归的数组的最小值.这是怎么回事
- 数组元素打印的递归方法
- 使用递归模板动态分配的多维数组
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 这种用于查找连续子数组中最大和的递归算法有什么优势吗?
- 使用递归输出数组
- 使用递归反转和打印出数组的内容
- 递归二进制搜索与字符串数组
- 将数组传递给递归函数,同时C++修改它
- 使用递归的序列到达数组末尾的最小跳转次数
- 这是定义一组递归规则的正确方法吗?
- 斐波那契数的递归函数
- 尝试递归获取数组元素的总和
- 在C++中对二维数组进行归零.循环需要2个吗
- C++排序数组递归
- 当我的编译器不符合标准时,如何将数组成员归零
- 数独递归,接受零为合法
- 通过除数组递归地计算和
- 动态数组递归与不同的编译器
- 不使用循环和数和的数字根递归