/第七行中如果写成:for(m=1;m<=100;m=m+2)然后底下删去十一和十二行, 就可以输出除2外所有素数/
//那么如果要输出加上2的素数,我的这个程序错在哪(输出结果是2、3交替不停输出,都看不清
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int m,n,k;
for(m=1;m<=100;m=m+1)//7
{ bool prime=true;
k=int(sqrt(float(m)));
for(n=2;n<=k;++n)
{if (m=2)//11
break;//12
else if(m%n==0)
{prime=false;
break;}
}
if (prime==true)
cout<<m<<endl;
}
return 0;
}
PHP中文网2017-04-17 14:21:33
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int m,n,k;
for (m=1; m<=100; m++) {
bool prime = true;
k = int(sqrt(float(m)));
for (n=2; n<=k; n++) {
if (m=2) { // 問題在此, 應改為 if (m==2)
break;
}
else if (m%n==0) {
prime = false;
break;
}
}
if (prime==true) {
cout << m << endl;
}
}
return 0;
}
The error in this line will cause the first printed value to be 1, and then 2 and 3 will be staggered.
Why? First of all, m==1
will not enter the inner for loop but at this time prime
is true
, so you will print out 1.
It is normal when m==2
and m==3
are used. Neither of them will enter the inner for loop, and then they will be printed out.
Then when m==4
is entered, the inner for loop is entered, but in the if (m=2)
step, m
is set to 2 and leaves the loop. At this time, prime
is still true
Causes 2 duplicates to be printed.
Then m
the next cycle will become 3 (2+1), at this time 3 is printed repeatedly.
Then you and I both understand, m==4
it will make everything fall into an unextricable cycle.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int m,n,k;
for (m=2; m<=100; m++) {
bool prime = true;
k = int(sqrt(float(m)));
for (n=2; n<=k; n++) {
if (m==2) {
break;
}
else if (m%n==0) {
prime = false;
break;
}
}
if (prime==true) {
cout << m << endl;
}
}
return 0;
}
It’s very simple. First, change m=2
to m==2
. Secondly, in order to avoid 1 being printed, I suggest that the outer for should start directly from 2.
The layout of the code is very important and will affect the readability. It is recommended to have your own set of logic and try to arrange it as beautifully as possible
It is recommended to have clear layers (remember to indent the inner blocks)
Don’t be too crowded with code
I personally recommend adding if/else/for
to even single-line {}
, which is unified, easy to read and less likely to cause problems
You can try to extract and write function
Next time you encounter an error, you can simulate the computer and run a loop two or three times. It is easy to catch the problem
Questions I answered: Python-QA