我必須返回兩個數字,其階乘和等於10!兩個數字應該返回數組中。我已經完成了如下代碼,但是它找不到任何這樣的兩個數字。它以「堆棧溢出異常」結束。 我的代碼是:什麼是兩個數字x和y,使得x和y的階乘和等於階乘10
private int[] solve10()
{
int[] n = new int[2];
bool found=false;
int c1 = 1;
int fact1 = 0;
int fact2 = 0;
int fact10 = 0;
try
{
fact10 = findFactorial(10);
while(!found)
{
fact1 = findFactorial(c1);
for (int j = 1; j < 10;j++)
{
fact2 = findFactorial(j);
if (fact1+fact2==fact10)
{
n[0] = c1;
n[1] = j;
found = true;
break;
}
}
c1++;
}
return n;
}
catch (Exception ex)
{
throw ex;
}
}
findFactorial是一個返回factorial的函數。其定義如下
private int findFactorial(int n)
{
int fact = 0;
try
{
if(n==0 || n==1)
{
fact= 1;
}
else
{
fact= n * findFactorial(n - 1);
}
return fact;
}
catch (Exception ex)
{
throw ex;
}
}
這在前面[SO Post]中討論過(http://stackoverflow.com/questions/25135435/c-sum-of-two-factorials-euals-factorial-of-10-find-two-values-say -x-and-y-whos),更有趣的是答案中的「點3」。 –
爲什麼你在那裏有一個'try' /'catch'塊?你期待什麼異常會拋出你可以從中恢復? – Enigmativity
我沒有注意到,但是你都有'try' /'catch'。這是你如何寫你的所有代碼?這是一個不好的做法。 – Enigmativity