我试图在 C++ 中找出如何找到一个范围内的所有素数(现在使用 100)
我不关心性能,我从 C++ 开始,并试图从我的书中理解这个程序练习。我在下面尝试使用我的程序,但它一直返回 false。有任何想法吗?我已经阅读了几乎所有 googles/bing 的帮助以及堆栈溢出。我可以为它编写代码来输入数字;只是不遍历所有数字
关于我做错了什么的想法?
#include <iostream>
using namespace std;
bool isPrime(long n);
int main()
{
int i;
//some vars
char emptyVar;
//first loop (to increment the number)
for (i = 0; i <= 100; i++)
{
//checking all numbers below 100
if (isPrime(i) == true)
{
//is true
cout << i << ", ";
}
else if (isPrime(i) == false)
{
//is false
cout <<"false , ";
}
}
cin >> emptyVar;
}
bool isPrime(long n)
{
long i =0;
//checks to see if the number is a prime
for (i = 2; i < n; i++) // sqrt is the highest possible factor
{
if ( n % i == 0) // when dividing numbers there is no remainder if the numbers are both factors
{
// is a factor and not prime
return false;
}
else if (n % i != 0 && i >= 100)
{
//is not a factor
return true;
}
}
}
最佳答案
isPrime
函数没有针对每个可能的执行路径的 return
语句。例如,当 n == 2
时,isPrime
做什么?
下面是 for
循环的工作原理(伪代码)。一般语法是
for (initialiazion; condition; increment) {
body;
}
rest;
这可以转化为 while
循环:
initialiazion;
while (condition) {
body;
increment;
}
rest;
特别是,条件
在初始化
之后,body
被执行之前检查。
我怀疑,您认为 for
循环是这样工作的:
initialiazion;
do {
body;
increment;
} while (condition);
rest;
即在第一个增量
之后检查条件。但事实并非如此。
关于c++自动判断素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15056063/