我的问题与C ++的基础有关。
我编写了以下代码来检测素数并最多计数5个素数,然后终止。
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int count = 0, x;
int i = 2;
double rem;
while (count < 5)
{
cout << "Enter an integer number to check it : ";
cin >> x;
if (x < 2)
{
cout << x << " is not a prime number." << endl;
continue; //start from the beginning again
}
else
{
for (int i = 2; i < x; ++i);
{
rem = remainder(x, i);
if (rem == 0)
{
cout << x << " is not a prime number.";
break;
}
}
cout << x << " is a prime number." << endl;
count += 1;
}
}
return 0;
}
我的问题是使用“ break”时,它打破了整个“ while”循环,而不仅仅是“ for”。
我在了解其功能时错过了什么吗?
[如果只想为一个循环使用类似中断的功能,只需将循环的结束条件放在代码中,该条件对于您的代码将是i=x;
-放置该循环而不是中断,它将根据需要终止循环。