查找100阶乘的逻辑错误
Logical error in finding 100 factorial
我正在尝试计算任何整数的阶乘,但会出现一些随机输出。
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++)
循环内的for
和while
循环分开。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;
}
}
相关文章:
- 在 C++ 中的数组上使用阶乘函数
- 阶乘问题在 c++ 中给出错误的输出
- 大数的阶乘给出错误的输出
- 什么模板用法在阶乘中更好
- 为什么我在C++阶乘函数中出现编译错误?
- 计算阶乘的 C++17 倍表达式中的错误
- 为什么 Lisp 中 1000 阶乘的计算如此之快(并显示正确的结果)?
- 在C++中执行 N 阶乘编译时间的 3 种不同/相同方法
- 平方模型为零,阶乘模型问题
- 阶乘元规划
- 阶乘-c++ 我想以不同的方式打印
- 阶乘代码厨师错误 (C++)
- 简单C++脚本 - 阶乘 - 错误
- 在 C++ 中,数字阶乘的自写代码中的错误
- 带有值的递归阶乘错误返回语句,在函数中返回 'void' [-fallowive]
- 程序以查找数字的阶乘并为负整数输入提供错误消息
- 错误的输出 - 拉马努金阶乘和C++的近似
- 阶乘在main中显示错误的答案.在函数中正确计算
- 查找100阶乘的逻辑错误
- 如何在c++中实现阶乘函数并进行正确的错误处理