试图弄清楚如何使用递归来获得与另一个函数相同的答案

Trying to figure out how to use recursions to get the same answer as another function

本文关键字:函数 另一个 答案 弄清楚 何使用 归来 递归      更新时间:2023-10-16

我可以在编程作业中使用一些帮助。我需要使用递归才能使arithmetic_series = arithmetic_series_recursive。现在我的递归函数无法正常工作。它只工作到数字三。这些函数应该从用户那里获取输入,并根据数字内的整数数形成一个数字。IE 如果用户输入 3,则为 1*2*3 = 6。

int arithmetic_series(int n){
    int total = ((n+1) * n )/ 2;
    cout << total << endl;
    return total;
}
int arithmetic_series_recursive(int n){
    if(n==1){
            return 1;
    }else{
    return n*arithmetic_series_recursive(n-1);
    }
}

你的第一个函数找到从 1n 的整数之和。您的第二个函数查找该范围的乘积,或!n 。我不知道您可以在第一个函数中使用任何简化。

如果你想找到数字的总和,你可以改变你的第二个函数来执行加法:

int arithmetic_series_recursive(int n) {
    if (n == 1) {
        return 1;
    }
    else {
        return n + arithmetic_series_recursive(n - 1);
    }
}