gpt4 book ai didi

c++ - 如何避免 bad_alloc?

转载 作者:太空宇宙 更新时间:2023-11-04 12:01:46 26 4
gpt4 key购买 nike

<分区>

如何避免下面代码中的 bad_alloc 错误。它说 C调用了 abort 函数:

terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
SIGABRT

#include<iostream>
#include<math.h>
#include<conio.h>
using namespace std;
int main()
{
int n,p,count=0;
double l,t;
while(1)
{
cin>>n;
if(n==0)
break;
else
{
int * arr;
arr= new int[n+1];
for (int i=1; i<=n; i++)
arr[i]=0;
for(int i=2;i<=n;i++){
if(arr[i]==0)
{ p=i;
count++;
for (int j=2;p*j<=n;j++)
{
arr[p*j]=1;
}
}

}
delete[] arr;
l=(double(n))/(log(n));
t=(((count-l))/count)*100;
if(t<0)
t=(-1)*t;
printf("%.1lf\n",t);
}
count=0;
}
getch();
return 0;
}

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