C语言 c - 如何在数组中找到最大和最小的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3796936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:32:17  来源:igfitidea点击:

How to find the largest and smallest number in an array in c

carraysmaxmin

提问by smooth_smoothie

I have to find a way to display the Maximum and Minium number in an array, the size of the array is 100 and will not exceed that and there is not need for input validation. The program will keep asking for input until 0 is encountered and it too will get added to the array.

我必须找到一种方法来显示数组中的最大值和最小值,数组的大小为 100,并且不会超过该值,并且不需要输入验证。程序将不断要求输入,直到遇到 0,它也会被添加到数组中。

I have everything figured out except how to keep track which is the largest and smallest value. I'd appreciate it if someone can fix my code or show me.Another problem I'm having is getting the loop to terminate and do max/min calculation within the while loop when the input is equal to 0.

除了如何跟踪最大值和最小值之外,我已经弄清楚了一切。如果有人可以修复我的代码或向我展示,我会很感激

/*
 ============================================================================
 Name        : test.c
 Author      :
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#define n  100
int main(void){


 int numbers[n];
 int i = 1;
 int j;
        int input;
 int maxvalue;
 int minvalue;

   printf("Enter the next array element>");

input = scanf("%d", &numbers[100]);



while (input != 0){

  numbers[i] = input;
  i++;
  printf("Enter the next array element, while loop>");
  input = scanf("%d", &numbers[n]);
  if (input == 0){
printf("Enter the next array element, if loop");
   numbers[i] = 0;

   for (j =2;j <= i; j++){
    minvalue = numbers[1];

    j++;
    if (numbers[j] > minvalue){
     maxvalue = numbers[j] ;
    }
    else{
     minvalue = numbers[j] ;
    }

   }


  }
 }


printf("%f\t", maxvalue);

printf("%f\n", minvalue); 
 }

EDIT: I took all off your suggestions and edited my code. This is my code below. However, it's output isnt what I'm expecting.

编辑:我取消了您的所有建议并编辑了我的代码。这是我下面的代码。但是,它的输出不是我所期望的。

#include <stdio.h>
#include <stdlib.h>
#define N  100
int main(void){


    int numbers[N];
    int i = 0;
    int j;
        int input;
    int maxvalue;
    int minvalue;

            printf("Enter the next array element>");

scanf("%d", &input);



while (input != 0){

        numbers[i] = input;
        i++;

        if (input == 0){
                   i++;
            numbers[i] = 0;
                        minvalue = numbers[0];
                        maxvalue = numbers[0];
                        for (j=0;j<=i-1;j++){

                            if (minvalue >= numbers[j]){
                                minvalue = numbers[j];
                            }else if (maxvalue <= numbers[j]){
                                maxvalue = numbers[j];
                            }


                        }

/* min = value of first array element
max = value of first array element

begin loop for each array element, index = 0 to (n-1)

--- if array element value is less than min, set min to this value
--- if array element value is more than max, set max to this value

increment index and repeat loop til last index is completed

average = sum / number of elements (n).
max and min will hold their correct values.*/




        }
                printf("Enter the next array element, while loop>");
    scanf("%d", &input);
    }


printf("%d\t", maxvalue);
printf("%d", minvalue);
    }

This is the output, I'm getting! Can someone solve this for me.

这是输出,我得到了!有人可以为我解决这个问题。

Enter the next array element>1
Enter the next array element, while loop>2
Enter the next array element, while loop>3
Enter the next array element, while loop>0
12190144 l6Press [Enter] to close the terminal

FINAL EDIT: I SOLVED THIS ON MY OWN. I put the min/max checking outside the master WHILE loop, this allowed the input of 0 to be entered in the array.

最后编辑:我自己解决了这个问题。我将最小/最大检查放在主 WHILE 循环之外,这允许在数组中输入 0 的输入。

#include <stdio.h>
#include <stdlib.h>
#define N  100
int main(void){


    int numbers[N];
    int i = 0;
    int j;
        int input;
    int maxvalue =1;
    int minvalue = 1;
            printf("Enter the next array element>");

scanf("%d", &input);
minvalue = input;
maxvalue = input;



while (input != 0){
    numbers[i] = input;

    ++i;
                printf("Enter the next array element>");
    scanf("%d", &input);

if (input == 0){
numbers[i] = 0;
  ++i;

  }

}
for (j =0;j<i;j++){
 if (numbers[j] >= maxvalue){
                                maxvalue = numbers[j];
                            }
                            if(numbers[j] < minvalue){
                                minvalue = numbers[j];
                            }

}

printf("%d\t", maxvalue);
printf("%d\n", minvalue);

    }

回答by

First of all, you're assigning inputto the return value of scanf(). This is the number of items assigned by the call, and since you say the input will always be correct, this value will always be 1.

首先,您要分配inputscanf(). 这是调用分配的项目数,并且由于您说输入将始终正确,因此该值将始终为1

Secondly, you're writing past the end of the numbers[]array with the line:

其次,您正在numbers[]使用以下行写入数组的末尾:

input = scanf("%d", &numbers[100]);

(you should do scanf("%d, &input)instead, and assign numbers[i]to input in your loop.

(你应该这样做scanf("%d, &input),并分配numbers[i]给循环中的输入。

Finally, you don't need to recalculate maxvalueand minvalueby iterating through numbers[]every iteration of your loop. Instead, just compare them to inputand assign them accordingly.

最后,您不需要重新计算maxvalueminvalue遍历循环的numbers[]每次迭代。相反,只需将它们input与它们进行比较并相应地分配它们。

Hopefully this puts you on the right track.

希望这能让你走上正轨。

回答by DigitalRoss

It looks like your central problem is that you compare each number only against minvalue. That's fine for deciding whether to replace the current minvalue, but obviously it doesn't tell you anything about the relationship of each element to maxvalue.

看起来您的核心问题是您仅将每个数字与minvalue. 这对于决定是否替换当前的 来说很好minvalue,但显然它并没有告诉你每个元素与 的关系maxvalue

Another problem: it makes sense to initialize minvalue from the first element, but not if you do it in the loop. That just invalidates all your prior work.

另一个问题:从第一个元素初始化 minvalue 是有意义的,但如果你在循环中进行初始化则不然。这只会使您之前的所有工作无效。

You need to do the same initialization with maxvalue as well. You should initialize that number to the first value.

您还需要对 maxvalue 进行相同的初始化。您应该将该数字初始化为第一个值。

You should also make a decision about calculating the min and max as you accumulate the data or in a pass through the data when done. What you don't want to do, however, is loop through past elements with every new one. That gives your program quadratic time complexity for no benefit.

您还应该在累积数据或完成数据传递时决定计算最小值和最大值。然而,您不想做的是用每个新元素循环过去的元素。这使您的程序二次时间复杂度没有任何好处。

Finally, don't tolerate crummy formatting. Debugging always involves studying the code and you will want it to always be perfectly formatted both to be professional about things and also to facilitate reading your own work.

最后,不要容忍糟糕的格式。调试总是涉及研究代码,你会希望它总是完美地格式化,既专业又方便阅读你自己的作品。

回答by Jens Gustedt

You are asking two questions, about the strategy for the min / max computation and for the loop. Don't do that (to yourself) but solve one problem at a time. So first put something like

您在问两个问题,关于最小/最大计算和循环的策略。不要(对自己)那样做,而是一次解决一个问题。所以首先把类似的东西

signed int input[] = { 8, -5 , /* some more values */ };
size_t const n = sizeof input/ sizeof input[0];

at the start and forget about your scanfproblems.

一开始就忘记你的scanf问题。

Then wrap your min/max detection in the appropriate loop instruction.

然后将您的最小/最大检测包装在适当的循环指令中。

Then compile your code with warnings on: e.g -Wallfor gcc, but this might vary for your compiler.

然后编译带有警告的代码:例如-Wallfor gcc,但这可能因您的编译器而异。

Mine the tells me something:

我的告诉我一些事情:

test-numbers.c:21: warning: 'maxvalue' may be used uninitialized in this function test-numbers.c:22: warning: 'minvalue' may be used uninitialized in this function

test-numbers.c:21: 警告: 'maxvalue' 可以在这个函数中未初始化使用 test-numbers.c:22: 警告: 'minvalue' 可以在这个函数中使用未初始化

This tells you that you are doing something very wrong in not considering the starting point of your algorithm well.

这告诉您,您没有很好地考虑算法的起点,这是非常错误的。

回答by pmg

I've reindented your code and replaced lots of it with `/* ...PLACEHOLDER... */

我已经重新缩进了你的代码,并用 `/* ...PLACEHOLDER... */

#include <stdio.h>
#include <stdlib.h>
#define N  100
int main(void) {
    int numbers[N];
    int i = 0;
    int input;
    int maxvalue;
    int minvalue;

    printf("Enter the next array element>");
    scanf("%d", &input);

    while (input != 0) {
        numbers[i] = input;
        i++;

        if (input == 0) {
            /* ...PLACEHOLDER... */
        }
        printf("Enter the next array element, while loop>");
        scanf("%d", &input);
    }
    printf("%d\t", maxvalue);
    printf("%d", minvalue);
}

Hopefully you can see what happens when you enter 1, or 2, or 3 and when you enetr 0.

希望您能看到当您输入 1、2 或 3 以及输入 0 时会发生什么。

Hint: maxvalueand minvaluevalues are never changed.

提示:maxvalueminvalue值永远不会改变。

Another hint: how many times does the while()line execute?

另一个提示:该while()行执行多少次?



Editwith example run

使用示例运行进行编辑

For this example run, code is on the left side, what happens is on the left side

对于此示例运行,代码在左侧,发生的事情在左侧

        printf("Enter the next array element>"); |
        scanf("%d", &input);                     | Enter 42
                                                 |
        while (input != 0) {                     | input is 42, so you do the loop
            numbers[i] = input;                  | numbers[0] = 42
            i++;                                 | i = 1
                                                 |
            if (input == 0) {                    | input != 0; skip placeholder
                /* ...PLACEHOLDER... */          |
            }                                    |
            printf("Enter the next ...>");       |
            scanf("%d", &input);                 | enter 3
        }                                        | 
        while (input != 0) {                     | input is 3
            numbers[i] = input;                  | numbers[1] = 3
            i++;                                 | i = 2
                                                 |
            if (input == 0) {                    | input != 0; skip placeholder
                /* ...PLACEHOLDER... */          |
            }                                    |
            printf("Enter the next ...>");       |
            scanf("%d", &input);                 | enter 0
        }                                        | 
        while (input != 0) {                     | input is 0, skip while body
            /* ...PLACEHOLDER... */              |
        }                                        |
        printf("%d\t", maxvalue);                | maxvalue hasn't been initialized
        printf("%d", minvalue);                  | minvalue hasn't been changed

回答by user411313

int cmp(const void *a,const void *b)
{
  return *(const int*)a-*(const int*)b;
}
...
qsort( numbers, 100, sizeof(numbers[0]), cmp );
printf("\nmin: %d\nmax: %d",numbers[0],numbers[99]);