나의 발자취

[10818] 최소, 최대 본문

computer language/C++

[10818] 최소, 최대

달모드 2020. 11. 18. 10:33
#include <iostream>
using namespace std;

int main(void){
  int a, b, max, min;
  cin >> a;
  int arr [a] ;
  max,min = arr[0];
  for (int i; i < a; i++){
    cin >> b;
    arr[i]=b;
    
    if (arr[i] > max) max = arr[i];
    if (arr[i] < min) min = arr[i];
    
    
  }
  cout << min << " " << max ;
  return 0;

  
} 

 배열을 입력받고 그 안에서 최소값과 최대값을 출력하는 코드이다. 근데 실행결과가 자꾸만 이상하게 나오는것이다..

input

5
20 30 40 50 60
output

0 60

 

이렇게...그래서 스택에 질문을 올렸더니 곧이어 수많은 답변이 달렸다.

 

1. 대다수가 compiler waring을 켜라고 했다. 코드의 에러를 볼 수 있다고.

And always use compiler warnings (-Wall -Wextra on gcc/clang, /W3 on MSVC)

MSVC이기때문에 /W3으로 컴파일러 경고를 켤 수 있다.

 

gcc.godbolt.org/z/61zebx

 

Compiler Explorer - C++ (x86-64 clang (trunk))

using namespace std; int main(void){ int a, b, max, min; cin >> a; int arr [a] ; max,min = arr[0]; for (int i; i < a; i++){ cin >> b; arr[i]=b; if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; } cout << min << " " << max ; return 0; }

gcc.godbolt.org

컴파일이 되는 과정과 어셈블리 코드를 해석해가면서 어디가 문제인지 알 수 있다.

 

 

 

 

2. WTB some initial values. Insert canned VLA-non-standard C++ spiel here. And yes, there are several errors in your code, at least one of which should be flagging warnings you should be treating as errors. And just fyi, there is zero need for any array for this task. Give it some thought and think about just how important (or not) all the values except the running minimum and maximum are at any given moment, and thereafter the loop ->배열 문제라서 어쩔수가 없다 ㅠㅠ 하지만 배열을 쓰지 않고도 푸는것도 해봐야된다

--> 초기값 설정이 빠졌다.. for loop 에서 i 초기값이 

--> VLA(Variable-Length Array) : 가변길이 배열인데 이것이 지원이 될 수도 안될 수도 있다.(컴파일러에 따라 다르다) standard C++에서는 VLA가 지원되지 않지만, 확장버전의 컴파일러(gcc, clang)가 있다. 그래서 VLA를 표준 C++컨테이너로 대체하라고 하는데 (예: std::vector)

--> 최소값과 최대값을 구할 수 있는 표준 알고리즘이 있다: std::minmax

     #include <algorithm> 쓰고 minmax() 쓰면 된다.

 

<동적할당>

에서는 new[], delete[]을 이용하여 동적할당을 한다.

#include <iostream>
using namespace std;
 
int main(void) {
    int *p = new int[5];
 
    for (int i = 0; i < 5; i++) {
        p[i] = i + 1;
    }
 
    for (int i = 0; i < 5; i++) {
        cout << p[i] << "\n";
    }
 
    delete[] p;
 
    return 0;
}


출처: https://yeolco.tistory.com/117 [열코의 프로그래밍 일기]

 

3. arr[0]이 생성되기도 전에 max, min을 arr[0]으로 초기화해서 에러가 발생했다.

 

4. max, min = arr[0]으로 하면 (max, min) = arr[0]으로 파싱된다. The comma operator in max, min evaluates every operand and the result of the operator is the last operand, i.e. max is discarded and only min is assigned.즉

콤마 기준으로 왼쪽 변수인 max 는 버려지고 min에만 할당이 된다.

 

 

<라이브러리 사용>5800KB, 460 ms 

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main(void){
  int a, b, max, min;
  cin >> a;
  int arr [a] ;

  for (int i=0; i < a; i++){
    cin >> b;
    arr[i]=b;

 
  }
  cout << *min_element(arr, arr + a) << " " << *max_element(arr, arr + a);
} 

<라이브러리 사용 없이> 5800KB, 460 ms 

#include <iostream>
using namespace std;

int main(void){
  int a;
  cin >> a;
  int arr [a] ;

  int max = -1000000;
  int min = 1000000;
 
  for (int i=0; i < a; i++){
    cin >> arr[i];
    
    if (arr[i] > max) max = arr[i];
    if (arr[i] < min) min = arr[i];
    
    
  }
  
  cout << min << " " << max ;
  return 0;
  
} 

<배열 사용하지 않고 문제 풀기>

#include <iostream>
using namespace std;

int main(void){
    int a, b, max, min;
    cin >> a;

    cin >> b;
    min = max = b;

    for (int i = 1; i < a; i++) {
        cin >> b;

        if (b > max) 
            max = b;
        if (b < min) 
            min = b;
    }
    cout << min << " " << max ;
    return 0;
} 

 

 

'computer language > C++' 카테고리의 다른 글

[2562]최댓값  (0) 2020.11.18
8393. 팩토리얼 계산 (풀이 두개, 메모리 비교)  (0) 2020.10.13
백준 1330. 시계  (0) 2020.10.07
백준 1008 - A/B 출력  (0) 2020.10.07
백준 11021번  (0) 2020.09.14
Comments