c++计算质数题目

来源:百度知道 编辑:UC知道 时间:2024/05/21 16:18:21
#include<iostream>
using namespace std;
int main()
{
int i,j,k,l;
l=0;
cout<<"Enter the number:"<<endl;
cin>>i;
k=i;

for(j=1;k<=j;k--)

if(i%k==0)
{
l++;
}

if (l<=2)
{
cout<<i<<"是质数"<<endl;
}
else
{
cout<<"不是质数"<<endl;
}

}
长期显示是质数,请问原因?逻辑上面是没有错误的吧?

#include<iostream>
using namespace std;
int main()
{
int i,j,k,l;
l=0;
cout<<"Enter the number:"<<endl;
cin>>i;
k=i;

for(j=1;j<=k;j++)

if(k%j==0)
{
l++;
}

if (l<=2)
{
cout<<i<<"是质数"<<endl;
}
else
{
cout<<"不是质数"<<endl;
}

}
你的程序中的逻辑有问题。
本程序在windows+VC6.0的系统上编译通过,并运行正确。

#include<iostream>
using namespace std;
int main()
{
int i,j,k,l;
l=1;
cout<<"Enter the number:"<<endl;
cin>>i;
k=i;

for(j=2;j<k;j++)
{
if(k%j==0)
{
cout<<"不是质数"<<endl;
l = 0;
break;
}
}

if(l) cout<<i<<"是质数"<<endl;

return 0;
}

你的for循环判断条件些错了,应该是
for