我有一个基本程序,可以计算 1 到 N。
但是,我需要打印导致“N”的总和的每一行。
例如:输入 -> 3
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
我需要通过递归来完成此操作,而无需在代码中使用任何循环。
感谢任何帮助。我似乎无法理解如何做到这一点。
#include <iostream>
using namespace std;
int sumToN(int n, int row);
int input;
int main()
{
cout << "Sum to: ";
cin >> input;
cout << sumToN(input, 1);
}
int sumToN(int n, int row)
{
if (row==n) // BASE CASE
{
cout << row << " = ";
return row;
}
else // RECURSIVE CASE
{
cout << row << " + ";
return (row + sumToN(n, row+1));
cout << endl;
}
}
最佳答案
看这个:
int sumToN(int n, int row);
void out(int n);
int input;
int main()
{
cout << "Sum to: \n";
cin >> input;
out(1);
}
void out(int n)
{
if( n > input) return;
cout << sumToN(n, 1)<<"\n";
out(n+1);
}
int sumToN(int n, int row)
{
if (row==n) // BASE CASE
{
cout << row << " = ";
return row;
}
else // RECURSIVE CASE
{
cout << row << " + ";
return (row + sumToN(n, row+1));
cout << endl;
}
}
输出:
关于c++ - 将 1 加到 N,在新行中打印每个总和(递归),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49568219/