【问题标题】:Unexpected Output Shown by Program in C++C++ 程序显示的意外输出
【发布时间】:2015-12-16 04:23:38
【问题描述】:
#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 的数字,它给出正确的输出
输入: 5
输出: 120
但是对于其他数字,它给出了错误的输出
输入: 9
输出: 8080预期输出: 362880
我无法找到我的逻辑错误 ....................
请,如果您能找到任何错误,请告诉我.......
..................................................... ..........
..................................................... ……

【问题讨论】:

    标签: c++ error-handling error-correction


    【解决方案1】:

    您结束乘法循环的条件 (while((pow!=0) || (x == 0))) 是错误的。这个循环需要一直运行到 i >= len, and pow != 0。

    如果是9,你会得到

    9
    72    * 8
    504   * 7
    524   * 6
    

    因为循环在 24 之后结束,因为 pow == 0 和 x == 2; 5 是之前遗留下来的。

    【讨论】:

    • 我无法理解。请详细回答...我在乘法循环后初始化 len 那么我之前如何使用它??
    • @NavneetC。您需要跟踪 len 每个循环,这样您就知道您当前的数字有多长,这样您就知道您的乘法必须走多远。就像我在上面所做的那样,在调试器中逐步完成您的代码,或者在纸上完成它。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 2015-09-20
      相关资源
      最近更新 更多