繁体   English   中英

程序查找C中最小的三个数字

[英]Program to find the the smallest three numbers in C

我如何修改我的代码以找到最小的三个数字。

    #include<stdio.h>
    int main(){
    int a[50],size,i,small;

    printf("\nEnter the size of the array: ");
    scanf("%d",&size);
    printf("\nEnter %d elements in to the array: ", size);
    for(i=0;i<size;i++)
      scanf("%d",&a[i]);


    small=a[0];
    for(i=1;i<size;i++){
      if(small>a[i])
        small=a[i];
    }
    printf("Smallest element: %d",small);

    return 0;
    }

数组的部分排序始终可以轻松解决问题。 如果您不想实现排序,则可以使用以下逻辑:

a=b=c=32767;
for(i=0;i<size;i++){
    if(x[i]<a){
        c=b;
        b=a;
        a=x[i];
    }
    else if(x[i]<b){
        c=b;
        b=x[i];
    }
    else if(x[i]<c){
        c=x[i];
    }
}
printf("three smallest elements: %d, %d, %d",a,b,c);

希望能有所帮助...

/* store the three smallest in a[0],a[1] and a[2]. */

void place_three_smallest(int* a, int i1, int i2, int i3)
{
    a[0] = std::min(i1,std::min(i2,i3));
    a[2] = std::max(i1,std::max(i2,i3));
    a[1] = i1+i2+i3-a[0]-a[2];
}

// ...   
place_three_smallest(a, a[0], a[1], a[2]);
int ii = 3;
for(i=1; i<size; i++) {
    if (a[i] < a[2]) {
        place_three_smallest(a,a[0],a[1],a[i]);
    }
}

/* the first 3 elements of a are the smallest three, in order for least to most */
return a;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM