【发布时间】:2020-09-01 15:25:48
【问题描述】:
我尝试创建一个计算组合的程序,并且我正在使用代码块我认为我的代码没有问题我从互联网上下载了用于 Mingw 的 gdb32,因为我的导师使用它并且默认情况下不包含它。我尝试了几个测试用例和不同的方法,包括递归和迭代,之前没有错误我曾经得到 id returned 1 exit status 错误但现在没有错误但输出不正确
#include <iostream>
using namespace std;
int factorial (int n)
{
int i=1,fact;
if(n==0)
{
return 1;
}
else
{
while(n!=0)
{
fact=i*n;
n--;
}
}
return fact;
}
int nCr(int n, int r)//Iterartive combinatrics
{
int num,den;
num=factorial(n);
den=factorial(r)*factorial(n-r);
return num/den;
}
int NCR (int n, int r)//recursive combinatrics
{
if (n==r||n==0)
{
return 1;
}
else{
return NCR(n-1,r-1)+NCR(n-1,r);
}
}
int main()
{
cout << nCr(5,2)<< endl;
cout << nCr(5,1)<< endl;
return 0;
}
【问题讨论】:
-
使用你的调试器找到你的错误。
-
显然你的代码确实有错误。老师不讲各种错误吗?
-
“即使我的代码没有错误,我也没有得到正确的输出” - 没有编译器错误不与您的程序没有错误相同。甚至没有关闭。
-
如果你没有得到正确的输出,那么根据定义你的程序有错误。您需要扩大对“错误”含义的理解。
-
@OP -- 为了简单起见 -- 如果你被要求编写一个程序来将两个数字相加,但程序却减去了这两个数字,那么代码将编译没有错误,但是该程序没有完成正确的任务。这基本上就是其他人所说的没有编译器错误和没有逻辑错误是两件不同的事情时所指的。
标签: c++ function loops recursion math