【问题标题】:C++, Learning, Basic Return PrimesC++,学习,基本返回素数
【发布时间】:2021-02-23 14:13:43
【问题描述】:

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

#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;
}

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

【问题讨论】:

    标签: c++ boolean primes


    【解决方案1】:

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

    其次,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;
    }
    

    【讨论】:

    • 为什么不让colador返回向量或者通过引用传递它
    【解决方案2】:

    您的代码中有几个问题,

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

    您需要在执行 for( int i=0; i&lt;=9; i++) 之前调用它

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 2011-03-17
      相关资源
      最近更新 更多