查找100阶乘的逻辑错误

Logical error in finding 100 factorial

本文关键字:错误 阶乘 查找      更新时间:2023-10-16

我正在尝试计算任何整数的阶乘,但会出现一些随机输出。
Compiler-Codeblocks
https://www.codechef.com/problems/FCTRL2/

 int main()
    {
    int t,i,n,x,j=1,temp=0;
    cin>>t;     //Number of test cases
    int m=1;
    int a[200];//Array to store maximum digit number
    a[0]=1;  
    while(t>0)
       {
       cin>>n;
       for(i=1;i<=n;i++)
         {
         for(j=0;j<m;j++)
           {
           x=a[j]*i+temp;
           a[j]=x%10;
           temp=x/10;
           while(temp!=0)
             {
              a[m]=temp%10;
              temp=temp/10;
              m++;
             }
          }
      }
      for(j=m-1;j>=0;j--)
      {
          cout<<a[j];
      }
      cout<<"n";
      t--;
   }
   return 0;
  }

首先,你的代码。它是丑陋的。请多使用空格和注释。要弄清楚某些变量代表什么需要一些时间。

考虑到这一点,我认为您需要将for(j = 0; j < m; j++)循环内的forwhile循环分开。while循环不应该在for循环中:

for(j = 0;j < m; j++)
{
    x= a[j] * (i+temp);
    a[j] = x%10;
    temp = x/10;
}
while(temp != 0)
{
    a[m] = temp%10;
    temp /= 10;
    m++;
}

当while循环修改m的值时,您的内部循环正在再次执行。你需要跳出这个循环。

这是一个解决方案,

bool done = false;
...
   for(i=1;i<=n;i++)
   {
     done = false;
     for(j=0;j<m;j++)
     {
       x=a[j]*i+temp;
       a[j]=x%10;
       temp=x/10;
       while(temp!=0)
         {
          a[m]=temp%10;
          temp=temp/10;
          m++;
          done = true;
         }
         if (done) break;
      }
   }