如果测试没问题又出现段错误,那大概率是数组开小了,因为本题要针对给出数字做输出,刚开始忘记了,结果没有输出。做题还是要小心一点
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=110000;
bool cmp(int b,int c)
{
return b>c;
}
int main()
{
int n;
cin>>n;
bool hashnum[maxn]={false};
int a[maxn],ans[maxn],num=0,temp;
for (int i=0;i<n;i++)
{
scanf("%d",&a[i]);
temp=a[i];
while (temp>1)
{
if (temp%2==0)
{
temp=temp/2;
hashnum[temp]=true;
}
else
{
temp=(3*temp+1)/2;
hashnum[temp]=true;
}
}
}
for (int i=0;i<n;i++)
{
if(hashnum[a[i]]==false)
{
ans[num++]=a[i];
}
}
sort (ans,ans+num,cmp);
for (int i=0;i<num;i++)
{
printf("%d",ans[i]);
if (i!=num-1)
{
printf(" ");
}
}
}
本文分享了一次编程经历,初始因数组容量不足导致段错误,通过调整数组大小并优化代码,成功解决了问题。文章强调了仔细检查和合理分配资源的重要性。
1693

被折叠的 条评论
为什么被折叠?



