1번 두 수 비교하기

문제

두 정수 A와 B가 주어졌을 때, A와 B를 비교하는 프로그램을 작성하시오.

 

입력

첫째 줄에 A와 B가 주어진다. A와 B는 공백 한 칸으로 구분되어 있다.

 

출력

첫째 줄에 다음 세 가지 중 하나를 출력한다. 

- A가 B보다 큰 경우에는 '>'를 출력한다. 

- A가 B보다 작은 경우에는 '<'를 출력한다. 

- A와 B가 같은 경우에는 '=='를 출력한다.

 

C++

#include <iostream>
#include <string>
using namespace std;
int main(){
    int a, b;
    cin >> a;
    cin >> b;
    string result = "";
    if (a > b)
        result = ">";
    else if (a < b)
        result = "<";
    else
        result = "==";
    cout << result;
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        string input = Console.ReadLine();
        string[] arr = input.Split(' ');
        int a = int.Parse(arr[0]);
        int b = int.Parse(arr[1]);
        if (a > b) input = ">";
        else if (a < b) input = "<";
        else input = "==";
        Console.WriteLine(input);
    }
}

 

Python

strInput = input()
arrInput = strInput.split(' ')
a = int(arrInput[0])
b = int(arrInput[1])
if a > b: 
    c = ">"
elif a < b: 
    c = "<"
else: 
    c = "=="
print(c);

 

파이썬의 경우 조건문 작성 시

if 조건 :

elif 조건 :

else :

 

방식으로 작성한다. 그리고 중요한 점은 파이썬의 변수의 범위는 함수 단위로 이루어지기 때문에 조건문 내부에서 선언된 c는 외부에서도 접근이 가능하다. 하지만 함수 내에서 변수를 선언했다면 외부에서 접근할 수 없다.

 

Node.js

const readline = require('readline');
const rl = readline.createInterface({
    input:process.stdin,
    output:process.stdout
});

rl.question('', (answer) =>{
    let input = answer;
    let arr = input.split(' ');
    let a = parseInt(arr[0], 10);
    let b = parseInt(arr[1], 10);
    let result;
    if (a > b) {
        result = ">";   
    }
    else if (a < b) {
        result = "<";    
    }
    else {
        result = "==";  
    } 
    process.stdout.write(result);
    rl.close();
});

 

node.js 에서 입력은 모듈을 사용하여 처리한다.

 

1. 'readline' 모듈을 사용하여 입력 인터페이스를 생성한다.

2. 'rl.question'을 사용하여 사용자로부터 숫자를 입력받는다.

 

더 축약한 코드

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('', (answer) => {
    const [a, b] = answer.split(' ').map(Number);
    const result = (a > b) ? '>' : (a < b) ? '<' : '==';
    process.stdout.write(result);
    rl.close();
});

 

map을 사용하여 입력된 값을 저장하고 삼항 연산자로 조건을 비교하여 코드를 단축시켰다.

 

728x90
반응형

+ Recent posts