递归分区(数论)函数的问题
示例:假设您的用户输入是 6。那么总和为 6 的序列数为 11(包括 6 本身)。我遇到的问题是,当用户输入 1 或 6 时它就可以工作,但如果不是,那就太离谱了,我不明白为什么。
如果需要,我可以提供有关该主题的更多信息。
#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;
}
Example: Let’s say your user input is 6. Then the number of sequences that sum up to 6 is 11 (including 6 itself). The problem I am having is that it works when the user enters 1 or 6, but if not it is way off and I can't figure out why.
I can give more info on the subject if needed.
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我读了你指出的维基文章,他们给出了一些如何构建递归定义函数的说明。它看起来与您的代码不同。下面的代码适用于我
您可以在此处测试此代码
I read wiki article you pointed out, they give some instructions how to build recursive defined function. It looks different then your code. The code below works for me
You can test this code here