我很快写了一个使用eratosthenes 的素数程序。运行程序时出现应用程序崩溃。我调试了它,它告诉我std::bad_alloc
。调试器不会告诉我发生异常的代码行,但会告诉我系统代码的哪一行。我的来源如下。我对 C++ 有点陌生。
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
using namespace std;
int main(int argc, char* argv[])
{
unsigned long long numt;
if(argc < 2) {
cout << "Usage: "<<argv[0]<<" <primes until...>" << endl;
return 1;
}
else if(atol(argv[1])) {
cout << "Usage: "<<argv[0]<<" <primes until...>" << endl;
return 1;
}
numt = atol(argv[1]);
vector<bool> primes(numt);
for each(bool b in primes) b = true;
primes[0] = false;
long double sqrtt = sqrt(numt);
for(unsigned long long l = 0; l<=sqrtt; l++) {
if(!primes[l]) continue;
for(unsigned long long cl = l; cl < numt; cl+= l) primes[cl] = false;
}
for(unsigned long long l = 0; l<numt; l++) if(primes[l]) cout << l;
return 0;
}
也请告诉我任何不良的编程习惯。