2014-03-30 27 views
0

如何修改我的代碼以找到最小的三個數字。程序找到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; 
    } 
+1

http://en.cppreference.com/w/cpp/algorithm/partial_sort – chris

+0

爲什麼在C++中使用'printf'? –

+4

因爲它的C標記爲C++。 – Biduleohm

回答

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); 

希望它幫助...

+0

如果x [0]是最小的元素,這是否工作? –

+0

感謝您指出錯誤...更正... –

+0

@deb_rider非常感謝您的幫助:))) – Dana

0
/* 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; 
+0

嘿,爲什麼它包含C程序中的C++名稱空間? –

+0

最初的標題是C++代碼。 –

+0

如果地點功能是: if(i2 i3)SWAP(i2,i3); a [0] = i1; a [1] = i2; a [2] = i3; –

相關問題