下面的代码中显示了一个被零除的错误。。我正在使用dosbox 0.74编译器
int chkpm(int,int);
void main()
{
int num,i,count=-1;
cout<<"Enter a numbern";
cin>>num;
for(i=0;i<=num/2;i++)
{
if(num%i==0)
{ //test
`enter code here`cout<<"num%i=0";
count=chkpm(num,i);
}
if(count>0)
{
cout<<i<<" ^ "<<count;
}
}
cout<<"bye test n";
getch();
}
int chkpm(int num,int i)
{
int j,flag=0; //flag will be true if i is not prime factor
int count=0; //to calculate power of prime factor
for(j=0;j<=i/2;j++) //to check for prime
{
if(i%j==0) //check for divisibility
{
flag=1; //that means i is not prime
break;
}
}
if(flag==0) //if factor i is prime,flag is 0
{
while(num%i==0) //keep dividing prime factor by num
{ count++; //to count power
num=num/i;
}
return count;
}
else return -1; //when flag=1, i.e. factor not prime
}
当我重新执行代码时显示错误,而不是在编译时我试过各种各样的输入,从零到正数。。。。。。。。。
如有任何帮助,将不胜感激
for(i=0;i<=num/2;i++)
{
if(num%i==0)
...
}
这里i
将从值0开始。%
的意思是取模,这实际上意味着要进行除法,因此在if条件下除以零。
在你的函数中,你有一个类似的逻辑错误:
for(j=0;j<=i/2;j++) //to check for prime
{
if(i%j==0)
...
}
如果你不修复main()
,那么函数的i
将等于零,这将造成更多的伤害。
使用void main()
,而不是典型的int main()
。你可能想看看这个相关的问题。然后在退出main()
之前添加一个return 0
。