示例:假设您的用户输入为6 那么总计6的序列数是11(包括6本身)。 :
我遇到的问题是,当用户输入1或6时,它可以正常工作,但是它是关闭的,我无法找出原因。
如果需要,Partition可以提供有关该主题的更多信息。
提前致谢。
#include <iostream>
using namespace std;
int sum(double number, int min, int & counter)
{
int temp=0, n;
n=number+temp;
if (number>=(n/2.0)+.5 && (number!=1))
{
number --;
temp ++;
while (number>=(n/2.0))
{
number --;
temp ++;
counter ++;
}
}
else if (number==1)
{
counter ++;
return 0;
}
sum(n-1, 1,counter);
return 0;
}
int main()
{
int counter=1;
double number;
cout << "-------------------------------------------------------\n"
<< "Please enter the number: ";
cin >> number ;
cout << "\n";
if (number!=1)
{
sum(number, 1, counter);
}
cout << "The total number of combinations that result in a sum of "
<< number << " is: " << counter
<< "\n-------------------------------------------------------\n";
return 0;
}
答案 0 :(得分:1)
我阅读了你指出的wiki文章,他们给出了一些如何构建递归定义函数的说明。它看起来与你的代码不同。下面的代码适用于我
#include <iostream>
using namespace std;
int sum(int k, int n)
{
if(k == 1 || n == 1)
return 1;
if(k < n)
return sum (k, k);
else if (k == n)
return 1 + sum (k, k-1);
else
return sum (k,n-1) + sum (k-n, n);
}
int main (void)
{
int counter=1;
double number;
cout << "-------------------------------------------------------\n"
<< "Please enter the number: ";
cin >> number ;
cout << "\n";
counter = sum(number, number);
cout << "The total number of combinations that result in a sum of "
<< number << " is: " << counter
<< "\n-------------------------------------------------------\n";
return 0;
}
您可以测试此代码here