下面的程序用于在给定数字集之间打印质数。但是当我跑步时,它并没有打印出素数。
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int z = 0;
cout << "Enter an integer: ";
cin >> a;
cout << "Enter another number: ";
cin >> b;
for (int i=a; i<=b; i++)
{
for (int j=2; j<i; j++)
{
if (i%j == 0)
{
z++ ;
break;
}
}
if (z == 0)
{
cout << i << endl;
}
}
}
This is output 我希望输出为2 3 5 7
答案 0 :(得分:-2)
尝试此代码段。我使用变量bool素数代替变量z:
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
cout << "Enter an integer: ";
cin >> a;
cout << "Enter another number: ";
cin >> b;
for (int i = a; i <= b; i++)
{
bool prime = true;
for (int j = 2; j<i; j++)
{
if (i%j == 0)
{
prime = false;
break;
}
}
if (prime)
{
cout << i << endl;
}
}