《奇数单增序列》
题目
蒜头君给了一个长度为 N(不大于 500)的正整数序列(正整数的值不超过 N),请将其中的所有奇数取出,并按升序输出。
输入格式
共 2行:
第 1行为 N;
第 2行为 N个正整数,其间用空格间隔。
输出格式
增序输出的奇数序列,数据之间以逗号间隔。数据保证至少有一个奇数。
Sample Input
10
1 3 2 6 5 4 9 8 7 10
Sample Output
1,3,5,7,9
题意
取出所有的奇数,并从小到大排列。
思路
用for嵌套if。
坑点
冒泡排序
代码
#include<stdio.h>
int main()
{
int num[505];
int ans[505];
int n,cnt=0;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&num[i]);
if(num[i]%2!=0)
{
ans[cnt]=num[i];
//printf("%d, ",ans[cnt]);
cnt++;
}
}
for(int i=0;i<cnt;i++)
{
int temp;
for(int j=i;j<cnt;j++)
{
if(ans[i]>ans[j])
{
temp=ans[j];
ans[j]=ans[i];
ans[i]=temp;
}
}
}
for(int j=0;j<cnt;j++)
{
printf("%d",ans[j]);
if(j!=cnt-1)
{
printf(",");
}
}
return 0;
{
int n,cnt=0;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&num[i]);
if(num[i]%2!=0)
{
ans[cnt]=num[i];
//printf("%d, ",ans[cnt]);
cnt++;
}
}
for(int i=0;i<cnt;i++)
{
int temp;
for(int j=i;j<cnt;j++)
{
if(ans[i]>ans[j])
{
temp=ans[j];
ans[j]=ans[i];
ans[i]=temp;
}
}
}
for(int j=0;j<cnt;j++)
{
printf("%d",ans[j]);
if(j!=cnt-1)
{
printf(",");
}
}
return 0;
}
}