用C语言编写,查找数组中的最值

2025-11-07 07:20:31

1、打开visual C++ 6.0-文件-新建-文件-C++ Source File

用C语言编写,查找数组中的最值

用C语言编写,查找数组中的最值

2、定义变量:

#include <stdio.h>

main()

{

    int a[20], max, min, i, j, k, n;                      /*定义数组及变量数据类型为基本整型*/

    j=0; k=0;

用C语言编写,查找数组中的最值

3、输入元素的个数:

    printf("please input the nunber of elements:\n");

    scanf("%d", &n);                                     /*输入要输入的元素个数*/

用C语言编写,查找数组中的最值

4、输入数据:

    printf("please input the element:\n");

    for (i = 0; i < n; i++)                              /*输入数据*/

        scanf("%d", &a[i]);

    min = a[0];

用C语言编写,查找数组中的最值

5、找出数组中最小的数:

    for (i = 1; i < n; i++)                              /*找出数组中最小的数*/

        if (a[i] < min)

        {

            min = a[i];

            j = i;                                  /*将最小数所存储的位置赋给j*/

        }

    max = a[0];

用C语言编写,查找数组中的最值

6、找出数组中的最大数:

    for (i = 1; i < n; i++)                              /*找出这组数据中的最大数*/

        if (a[i] > max)

        {

            max = a[i];

            k = i;                                  /*将最大数说存储的位置赋给k*/

        }

用C语言编写,查找数组中的最值

7、输出结果:

    printf("\nthe position of min is:%3d\n", j);          /*输出原数组中最小数所在的位置*/

    printf("距八the min number is:%3d\n", min);

    printf("the position of max is:%3d\n", k);                /*输出原数组中最大数所在的位置*/

    printf("the max number is:%3d\n", max);

    return 0;

用C语言编写,查找数组中的最值

8、完整的源代码:

#include <stdio.h>

main()

{

    int a[20], max, min, i, j, k, n;                      /*定义数组及变量数据类型为基本整型*/

    j=0; k=0;

    printf("please input the nunber of elements:\n");

    scanf("%d", &n);                                     /*输入要输入的元素个数*/

    printf("please input the element:\n");

    for (i = 0; i < n; i++)                              /*输入数据*/

        scanf("%d", &a[i]);

    min = a[0];

    for (i = 1; i < n; i++)                              /*找出数组中最小的数*/

        if (a[i] < min)

        {

          三眠改  min = a[i];

            j = i;                                  /*将最小数所存储的位置赋给j*/

        }

    max = a[0];

    for (i = 1; i < n; i++)                              /*找出这组数据中的最大数*/

        if (a[i] > max)

        {

            max = a[i];

            k = i;                              薪耻    /*将最大数说存储的位置赋给k*/

        }

    printf("\nthe position of min is:%3d\n", j);          /*输出原数组中最小数所在的位置*/

    printf("the min number is:%3d\n", min);

    printf("the position of max is:%3d\n", k);                /*输出原数组中最大数所在的位置*/

    printf("the max number is:%3d\n", max);

    return 0;

}

用C语言编写,查找数组中的最值

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢