자료구조&알고리즘
[230224] 프로그래머스 C++ 숫자 비교하기
capaca
2023. 2. 24. 13:24
당연히 if 문을 이용하여 이렇게 풀었는데 좀 다양한 방법이 있었다
#include <string>
#include <vector>
using namespace std;
int solution(int num1, int num2) {
int answer = 0;
if (num1 == num2) {
return 1;
} else {
return -1;
}
}
#include <string>
#include <vector>
using namespace std;
int solution(int num1, int num2) {
int answer = -1;
if(num1 == num2){
return 1;
}
return answer;
}
위에꺼 까지는 예상할 수 있었던 부분
#include <string>
#include <vector>
using namespace std;
int solution(int num1, int num2) {
int answer = 0;
return num1 == num2 ? 1 : -1;
}
c++의 if 문은 블록을 선언해도 되지만 선언하지 않아도 컴파일러에서 암시적으로 선언해준다
아래 예제처럼 해도 실행은 가능하다는 의미
#include <iostream>
int main()
{
std::cout << "Enter a number: ";
int x;
std::cin >> x;
if (x > 10)
std::cout << x << "is greater than 10\n";
else if (x < 10)
std::cout << x << "is less than 10\n";
else
std::cout << x << "is exactly 10\n";
return 0;
}