2015-12-16 18 views
0
#include <iostream> 

using namespace std; 

void long_fctrl(int num[], int f_num) // Function for Factorial 
    { 
    --f_num; // Decrement Number to multiply with Factorial Number. 
    int i = 0, pow = 0, x, j, len = 0, k = 0; 
    while(f_num > 1) // Loop for Factorial Number 
    { 
     i = 0; 
      do { // Loop to Multiply Two Array Number 
      x = (num[i]*f_num) + pow; 
      num[i] = x%10; 
      pow = x/10; 
      ++i; 
     }while((pow!=0) || (x == 0)); 
     --f_num; 
     if(k == 0) //Condition to Find the Length of Factorial Number in array 
     { 
      len = i; 
      k = 1; 
     } 
     if(i > len)// Condition for factorial array Length 
     len = i; 
    } 
    cout << "Your Number : \n"; 
    for(j = len-1; j >= 0; --j) // Loop for Output of Factorial Number.. 
     cout << num[j]; 
} 

int main() 
{ 
    cout << "Enter Number (1 - 100) : "; 
    int num, temp; 
    cin >> num;// num is the number of which we have to calculate Factorial. 
    if(num > 0 && num <= 100) 
    { 
     int fctrl[200] = {0}; 
     int i; 
     temp = num;// Temp initialize to Factorial Number.. 
     for(i = 0; temp!= 0; ++i,temp/=10) 
     { 
      fctrl[i] = temp%10; 
     } // Loop to insert user entered Number in Factorial Array... 
     long_fctrl(fctrl, num); //Giving Factorial Number in Array and also 
           //in the integer form to the Function 
    } 
    return 0; 
} 

計劃是在範圍1到計算階乘至100 ..
通過輸入數小於6它給正確的輸出
輸入:
輸出:
但對其他數它給輸出錯誤
輸入:
輸出:
預期輸出:
我無法找到我的邏輯錯誤................ ...
請,如果你能找到任何錯誤,告訴我.......
....................... .....................................
........... ..................................................按計劃在c中所示意外的輸出++

回答

0

您的條件結束您的乘法循環(while((pow!=0) || (x == 0)))是錯誤的。這個循環需要運行,直到我> = LEN, POW!= 0

在9的情況下,你會得到

9 
72 * 8 
504 * 7 
524 * 6 

因爲環路24,因爲戰俘之後結束= = 0和x == 2; 5從以前就剩下了。

+0

我無法理解。請詳細回答...並且我在循環乘法後初始化len,那麼如何使用它之前? –

+0

@NavneetC。你需要跟蹤每一個循環的len,所以你知道你現在的數字有多長,以便你知道你的乘法有多遠。像上面所做的那樣,將代碼放在調試器中,或者通過紙張工作。 – 1201ProgramAlarm

+0

謝謝!幫助... –

-1

如果您使用的是C++ IDE,例如(代碼塊)您應該調試您的程序並逐步檢查哪裏出了問題以及在哪裏。