c - C语言程序求最小的三个数

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

希望对你有帮助...

关于c - C语言程序求最小的三个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22748214/

相关文章:

c - c中的memcpy命令

c++ - 使用 sizeof 运算符在 C 和 C++ 中的不同输出

c - 如何将结构初始化为空?

c - 重新排列风格糟糕的 C 代码

c++ - 我如何使用 cryptimportkey 函数导入私钥来加密数据相同的结果使用导入的 key

Eclipse 中的 C 代码自动完成

c - 如何将 Mac 字符串转换为 C 中的字节地址

CUDA C 矩阵乘法

C - 基本指针问题

c - For 循环在 C 中产生意外结果