查找100阶乘的逻辑错误

时间:2015-07-31 16:51:52

标签: c++ computer-science

我正在尝试计算任何整数的阶乘,但是会有一些随机输出 编译器代码块
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;
  }

2 个答案:

答案 0 :(得分:2)

首先,你的代码。它很丑。请使用更多空格和评论。需要一段时间才能弄清楚某些变量代表什么。

考虑到这一点,我认为您需要将while循环内的for(j = 0; j < m; j++)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++; } 循环中:

{{1}}

^改为做。

答案 1 :(得分:0)

当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;
      }
   }
相关问题