簡體   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