简体   繁体   中英

Unexpected Output Shown by Program in C++

#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;
}  

Program is to Calculate Factorial with in range 1 to 100 ..
By inputting Number less than 6 it is giving correct Output
Input : 5
Output : 120
But For Other Number it is Giving Wrong Output
Input : 9
Output : 8080
Expected Output : 362880
I am not able to find my logical error ...................
Please, if you are able to find any error , tell me.......
............................................................
.............................................................

You condition to end your multiply loop ( while((pow!=0) || (x == 0)) ) is wrong. This loop needs to run until i >= len, and pow != 0.

In the case of 9, you'll get

9
72    * 8
504   * 7
524   * 6

because the loop ends after the 24 because pow == 0 and x == 2; the 5 is left over from before.

如果您使用的是C ++ IDE,例如(代码块),则应调试程序并逐步检查出什么地方以及哪里出了问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM