C++,学习,基础 Return 素数

C++, Learning, Basic Return Primes

我的目标是:程序return我制作的向量中的数字列表,它们是素数,代码是错误的,

#include <iostream>
#include <vector>
#include <math.h>
using namespace std;

vector < int > L;
bool mark[10];
void colador()
{
    fill(mark,mark+10, false);
    for(int i=2; i*i <=10; i++)
    {
        if(!mark[i])
        {
            L.push_back(i); 
            for(int j=i*i; j<=10; j+=i)
            {
                mark[j]=true;
            }
        }
    }
    for(int e=sqrt(10)+1; e<=10; e++)
    {
        if(!mark[e])
        {
            L.push_back(e);
        }
    }
}



int main()
{
    for( int i=0; i<=9; i++)
    {
        cout << L[i] << endl ;
    }
    return 0;
}

当我编译它时,程序没有显示任何东西。怎么了?

首先,一般的功能是不会通过定义自动执行的。你必须调用它们来执行它们。

其次,main()中的循环是错误的。它可能会在不检查的情况下读取超出范围。

还有你的colador()函数是错误的。数组 mark 只有 10 个元素(mark[0]mark[9]),但您正在访问超出范围 mark[10].

试试这个:

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm> // for std::fill()
using namespace std;

vector < int > L;
bool mark[10];
void colador(){
    fill(mark,mark+10, false);
    for(int i=2; i*i <=10; i++)
    {
        if(!mark[i]){
            L.push_back(i);
            for(int j=i*i; j<10; j+=i){mark[j]=true;} // use j<10, not j<=10
        }


    }
    for(int e=sqrt(10)+1; e<10; e++){ // use e<10, not e<=10
        if(!mark[e]){L.push_back(e);}

    }
}

int main(){
    colador(); // call the function

#if 1
    // for modern compiler (C++11 or later)
    for( int e : L ){cout << e << endl ;}
#else
    // for old compiler
    for( size_t i=0; i<L.size(); i++){cout << L[i] << endl ;}
#endif

    return 0;
}

你的代码中有几个问题,

最相关的是你的函数 void colador() 不会被自己调用...

你需要在执行 for( int i=0; i<=9; i++)

之前调用它