简体   繁体   English

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

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

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.我必须找到一种方法来显示数组中的最大值和最小值,数组的大小为 100,并且不会超过该值,并且不需要输入验证。 The program will keep asking for input until 0 is encountered and it too will get added to the array.程序将不断要求输入,直到遇到 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);

    }

First of all, you're assigning input to the return value of scanf() .首先,您将input分配给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 .这是调用分配的项目数,并且由于您说输入将始终正确,因此该值将始终为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 maxvalue and minvalue by iterating through numbers[] every iteration of your loop.最后,您不需要通过在循环的每次迭代中迭代numbers[]来重新计算maxvalueminvalue Instead, just compare them to input and assign them accordingly.相反,只需将它们与input进行比较并相应地分配它们。

Hopefully this puts you on the right track.希望这能让你走上正轨。

It looks like your central problem is that you compare each number only against minvalue .看起来您的核心问题是您仅将每个数字与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很好,但显然它没有告诉您每个元素与maxvalue的关系。

Another problem: it makes sense to initialize minvalue from the first element, but not if you do it in the loop.另一个问题:从第一个元素初始化 minvalue 是有意义的,但如果你在循环中进行初始化则不然。 That just invalidates all your prior work.这只会使您之前的所有工作无效。

You need to do the same initialization with maxvalue as well.您还需要对 maxvalue 进行相同的初始化。 You should initialize that number to the first value.您应该将该数字初始化为第一个值。

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.调试总是涉及研究代码,你会希望它总是完美地格式化,既专业又方便阅读你自己的作品。

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 scanf problems.在开始时忘记您的scanf问题。

Then wrap your min/max detection in the appropriate loop instruction.然后将您的最小/最大检测包装在适当的循环指令中。

Then compile your code with warnings on: eg -Wall for gcc , but this might vary for your compiler.然后编译带有警告的代码:例如-Wall for 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.这告诉您,您没有很好地考虑算法的起点,这是非常错误的。

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: maxvalue and minvalue values are never changed.提示: maxvalueminvalue永远不会改变。

Another hint: how many times does the while() line execute?另一个提示: while()行执行了多少次?


Edit with 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
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]);

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

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