简体   繁体   English

C 程序查找最大和最小元素时出错

[英]error in C program finding max and min element

Can anyone help me spot the error in my program in finding the minimum and maximum element in a agiven array.谁能帮我找出程序中的错误,即在给定数组中查找最小和最大元素。 I know that it is a simple error but I cannot figure it out.我知道这是一个简单的错误,但我无法弄清楚。

#include <stdio.h>
    # define SIZE 10
    int main()
    {
            int min;
            int max;
            int i; //counter variable
            int arr[SIZE] = {2,4,5,7,8,100,4,1};
    
            //check min and max of given array
            min = arr[0];
            max = arr[0];
            for(i =0; i< SIZE;i++)
            {
                    if(arr[i]<min)
                    {
                            min = arr[i];
                    }
                    if(arr[i]>max)
                    {
                            max = arr[i];
                    }
            }
            printf("minimum is %d\n",min);
            printf("maximum is %d\n",max);
    
            return 0;
    }

You are defining an array of 10 elements and initializing only 8 of them.您正在定义一个包含 10 个元素的数组并仅初始化其中的 8 个。 The remaining two array elements are zero-initialized .剩余的两个数组元素是零初始化的 That is why your min var is set to 0 .这就是为什么你的min var 设置为0

Alternatively define a macro to have a value of 8:或者将宏定义为值为 8:

#define SIZE 8

or define an array as following:或定义一个数组如下:

int arr[] = {2, 4, 5, 7, 8, 100, 4, 1};

and obtain the array size through the following expression where needed:并在需要时通过以下表达式获取数组大小:

sizeof(arr) / sizeof(arr[0])

With arrays of unknown size , the compiler deduces the array size based on the number of initializers, which in our case is 8 and it is the same as if we had written: int arr[8] .使用未知大小的 arrays 时,编译器根据初始化器的数量推断数组大小,在我们的例子中是 8,就好像我们写的一样: int arr[8]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM