如何解决C++,学习,基本返回素数
我的目标是:程序返回我制作的向量中的数字列表,是质数,代码有误,
#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++)
之前调用它
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。