如何修改我的代码以找到最小的三个数字。
#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;
}
答案 0 :(得分: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);
希望它有所帮助...
答案 1 :(得分: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;