【问题标题】:How to print only the second element of the sorted array?如何仅打印排序数组的第二个元素?
【发布时间】:2019-10-19 15:57:10
【问题描述】:

这里我已经按升序对数组进行了排序。现在我只想打印排序数组的第二个元素。下面的代码打印未排序数组的第二个元素。我能做些什么?

 #include <stdio.h>
 #include <string.h>
 #include <math.h>
 #include <stdlib.h>

 int main() {
 int n,b[n],i,j;

scanf("%d",&n);

for(i=0;i<n;i++)
    scanf("%d",&b[i]);
for(i=0;i<=n-2;i++)
{
    for(j=i+1;j<n;j++)
    {
        if(b[i]>b[j])
        {
           int a=b[i];
            b[i]=b[j];
            b[j]=a;

        }
    }

}

printf("%d",b[1]);

/* Enter your code here. Read input from STDIN. Print output to STDOUT */    
return 0;

}

【问题讨论】:

  • 看起来你已经这样做了?
  • 打开编译器警告并阅读它们。他们会告诉你一个严重的错误。
  • b[n], n 不确定。
  • 提示:n用于指定数组维度时的值是多少?
  • n 可以是任何正值

标签: c sorting arraylist


【解决方案1】:

问题是

int n,b[n],i,j;

当您声明b[n]n 是不确定的时,它可以有任何垃圾值,因此可能会在后期导致 UB。

从用户那里得到n后声明b

 int n,i,j;

 scanf("%d",&n);

 int b[n]; //or int *b = malloc(sizeof(int)*n); and later do free(b);

【讨论】:

    【解决方案2】:

    您应该将 n 定义为常量或使用 malloc 进行数组分配。

    #include <stdio.h>
    #include <string.h>
    #include <math.h> 
    #include <stdlib.h>
    #define n 5 
    int main() {
     int b[n],i,j;
    
     for(i=0;i<n;i++)
         scanf("%d",&b[i]);
    
     for(i=0;i<=n-2;i++) {
         for(j=i+1;j<n;j++)
         {
             if(b[i]>b[j])
             {
                int a=b[i];
                 b[i]=b[j];
                 b[j]=a;
    
             }
         }
    
     }
    
     printf("%d",b[1]);
    
     /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    return 0; 
    } 
    

    #include <stdio.h>
    #include <string.h>
    #include <math.h> 
    #include <stdlib.h>
    #include <malloc.h>
    int main() {
     int n,i,j;
     scanf("%d",&n);
    
     int *b = malloc(sizeof(int)*n);
    
     for(i=0;i<n;i++)
         scanf("%d",&b[i]);
    
     for(i=0;i<=n-2;i++) {
         for(j=i+1;j<n;j++)
         {
             if(b[i]>b[j])
             {
                int a=b[i];
                 b[i]=b[j];
                 b[j]=a;
    
             }
         }
    
     }
    
     printf("%d",b[1]);
    
     free(b);
     /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    return 0; 
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 2020-08-22
      • 2022-08-14
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多