카테고리 없음

[C ++] 최대 출력이 잘못되었습니다.

행복을전해요 2021. 2. 28. 23:36
if(min > sora[x]) {
    min=sora[x];
    }
    else if (max < sora[x])
    {
        max=sora[x];
        }
        

has the problem. The second else if statement is entered only if the first if is satisfied. But the second if has to be executed always. Please change the above block as follows

if(min > sora[x]) {
    min = sora[x];
    }
    if (max < sora[x]) {
        max = sora[x];
        }
        

And you are also using an uninitialized area to compare against. If you are using only positive numbers

max = 0;
min = UINT_MAX;

If you use negative numbers also, then

max = INT_MIN;
min = INT_MAX;

You have to include <limits.h> for these macros.

-------------------

You're initializing min and max to an undefined value when you do max= sora[0]; and min= sora[0];

Also, you have an else where you don't necessarily want one. The first value will be both the min and the max. You can start by setting max=0 and min=99, and that should solve that particular problem.

-------------------
sora = new int [num];   

max= sora[0];
min= sora[0];

이 줄은 가비지로 int 배열을 초기화하고 max와 min을 가비지 값으로 설정합니다.

두 가지 옵션이 있습니다.

  1. 시작시 최대 값을 가능한 가장 낮은 값 (INT_MIN)으로 초기화하고 최소값을 가능한 가장 높은 값 (INT_MAX)으로 초기화합니다.

  2. 먼저 임의의 값을 생성하고이를 sora [0]에 할당하고이 값에 대해 최대 값과 최소값을 초기화합니다. 그 후 [1..num] 초기화

-------------------

초기화되지 않은 메모리 위치를 읽고 있습니다.

sora = new int [num];   

max= sora[0];
min= sora[0];

를 사용하여 배열을 만들면 new해당 내용이 초기화되지 않습니다.

이로 인해 정의되지 않은 동작으로 알려진 현상이 발생하여 거의 모든 일이 발생할 수 있습니다. 이 경우에는 꽤 바닐라 일 것입니다. 임의의 값 (대부분의 0-99 범위 밖에있는 rand()%100)이 최소값과 최대 값에 저장되어 잘못된 결과가 자주 발생합니다.

대신

// must #include <limits>

int max = std::numeric_limits<int>::min();
int min = std::numeric_limits<int>::max();

아니면 그냥

int max = 0;
int min = 99;

범위가 미리 정의되어 있기 때문입니다.



출처
https://stackoverflow.com/questions/22089794