我正在学习编程:使用C++的原则和实践,我正在学习第 4 章,练习 11。这个问题希望你编写一个程序来检测 1 到 100 之间的所有素数。这就是我到目前为止所拥有的
//This program finds the prime numbers between 1 and 100
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
vector<int>primes;
bool ptest(int y)
{
int p=0, x=0;
for (x==0; x<primes.size(); ++p)
{
if (y%primes[x]==0)
{
return false;
}
return true;
}
}
int main()
{
int i=3;
primes.push_back(2);
vector<int>comp;
for (i==3; i<=100; ++i)
{
if (ptest(i)==true)
{
primes.push_back(i);
}
}
for (int x:primes)
{
cout << x << " ";
}
}
出于某种原因,程序打印 2,然后是 3-100 之间的所有赔率。我不确定我在这里错过了什么。
编辑:问题已得到解答。p
来自之前的尝试,我忘记更改。这里的主要错误是我不知道return true
值属于循环之外。谢谢
错误:
- 您的
return true;
处于错误的位置。它应该在循环之后。 -
x
必须在迭代中更新。
警告:
- 循环中
x==0
的第一个表达式for
毫无意义。 -
p
是没有意义的,因为它的值没有被使用。
试试这个:
bool ptest(int y)
{
for (int x=0; x<primes.size(); ++x)
{
if (y%primes[x]==0)
{
return false;
}
}
return true;
}