c++自动判断素数

标签 c++ loops numbers boolean primes

我试图在 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/

相关文章:

c++ - 制作功能 "const"的意图是什么

c++ - 用相同的值填充数组,循环重置值

javascript - 将两个 Uint32Array 值转换为 Javascript 数字

MYSQL:序号表

c++ - 为什么 C++20 允许默认比较即使被删除也能编译?

V8 中的 Javascript 等价物?

c++ - 可能正在学习旧的 C++ 标准

Java for 循环中的数组

JavaScript - 在迭代期间添加/删除对象数组的元素

loops - elisp: do 子句语法错误