gpt4 book ai didi

c++ - std::bad_alloc 在短质数程序中抛出

转载 作者:太空宇宙 更新时间:2023-11-04 15:19:28 25 4
gpt4 key购买 nike

我很快写了一个使用 eratosthenes seive 的素数程序。我在运行程序时遇到了 appcrash。我调试了它,它告诉我 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;
}

也请告诉我任何不良的编程习惯。

最佳答案

非常糟糕的做法:编译代码时没有打开所有合理的编译器警告,或者忽略编译器警告。

变量 numt 没有定义值。 vector primes (numt) 因此会失败。

关于c++ - std::bad_alloc 在短质数程序中抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22673960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com