3번 사분면 고르기

문제

흔한 수학 문제 중 하나는 주어진 점이 어느 사분면에 속하는지 알아내는 것이다. 사분면은 아래 그림처럼 1부터 4까지 번호를 갖는다. "Quadrant n"은 "제 n사분면"이라는 뜻이다.

https://www.acmicpc.net/problem/14681

 

예를 들어, 좌표가 (12, 5)인 점 A는 x좌표와 y좌표가 모두 양수이므로 제1사분면에 속한다. 점 B는 x좌표가 음수이고 y좌표가 양수이므로 제2사분면에 속한다. 점의 좌표를 입력받아 그 점이 어느 사분면에 속하는지 알아내는 프로그램을 작성하시오. 단, x좌표와 y좌표는 모두 양수나 음수라고 가정한다.

 

입력

첫 줄에는 정수 x가 주어진다. (−1000 ≤ x ≤ 1000; x ≠ 0) 다음 줄에는 정수 y가 주어진다. (−1000 ≤ y ≤ 1000; y ≠ 0)

 

출력

점 (x, y)의 사분면 번호(1, 2, 3, 4 중 하나)를 출력한다.

 

x 가 양수인지 음수인지, y가 양수인지 음수인지 구분해서 조건

 

C++

#include <iostream>
using namespace std;
int main(){
    int x, y;
    cin >> x;
    cin >> y;
    char result;
    if (x > 0)
    {
        if (y > 0)
            result = '1';
        else 
            result = '4';
    }
    else{
        if (y > 0)
            result = '2';
        else
            result = '3';
    }
    cout << result;
    return 0;
}

 

 

C#

using System;
class Program{
    static void Main(string[] args){
        string inputX = Console.ReadLine();
        string inputY = Console.ReadLine();
        int x = int.Parse(inputX);
        int y = int.Parse(inputY);
        char result;
        if (x > 0)
        {
            if (y > 0)
                result = '1';
            else 
                result = '4';
        }
        else{
            if (y > 0)
                result = '2';
            else
                result = '3';
        }
        Console.WriteLine(result);
    }
}

 

앞의 문제들과 다르게 각 줄에 값들이 들어온다. 따라서 입력을 따로 두 번 받아서 값을 저장한다.

 

Python

x = int(input());
y = int(input());
if x > 0:
    if y > 0:
        result = '1';
    else:
        result = '4';
else:
    if y > 0:
        result = '2';
    else:
        result = '3';
print(result);

 

파이썬에서 중첩 조건문을 쓸 때는 들여 쓰기로 구분한다.

 

Node.js

const readline = require('readline');
const rl = readline.createInterface({
    input : process.stdin,
    output : process.stdout
});
let x, y;
let result;
rl.question('', (answerX)=>{
    x = parseInt(answerX, 10);
    rl.question('', (answerY)=>{
    y = parseInt(answerY, 10);
        if (x > 0){
            if (y > 0)
                result = '1';
            else
                result = '4';
        }
        else{
            if (y > 0)
                result = '2';
            else
                result = '3';   
        }
        console.log(result);
        rl.close();
    });
});

 

각 각의 입력을 받고 처리한다.

rl.close()가 호출되면 입력된 값을 사용할 수 없기 때문에 호출 전에 결과를 출력해야 한다.

728x90
반응형

+ Recent posts