[프로그래머스] C++ 숫자

물론 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;
}