홀짝 구분하기

남예지·2024년 1월 27일
0

미코

목록 보기
18/37

문제

자연수 n이 입력으로 주어졌을 때 만약 n이 짝수이면 "n is even"을, 홀수이면 "n is odd"를 출력하는 코드를 작성해 보세요.

이상한 베이스코드가 주어졌다.

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

let input = [];

rl.on('line', function (line) {
    input = line.split(' ');
}).on('close', function () {
    n = Number(input[0]);
});

여기서 뭘 어떻게 하라는 걸까. 전에 콘솔로 치니까 되긴 되더라.

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

let input = [];

rl.on('line', function (line) {
    input = line.split(' ');
}).on('close', function () {
    n = Number(input[0]);
    
      if (n % 2 === 0) {
        console.log(`${n} is even`);
    } else {
        console.log(`${n} is odd`);
    }
});

console을 찍어보니 input, n이 전부 n이여서 당황스럽...
암튼 이 자리에 콘솔로 출력하면 되는 문제였다.

readline.createInterface는 Node.js의 readline 모듈에서 제공하는 인터페이스를 생성하는 메서드입니다. readline 모듈은 터미널에서 사용자의 입력을 처리하고 출력하는 데 유용한 기능을 제공합니다.

createInterface를 사용하여 인터페이스를 생성하면, 터미널 입력 스트림(process.stdin)에서 사용자의 입력을 읽고 출력 스트림(process.stdout)에 메시지를 출력할 수 있습니다. 이는 주로 사용자와 상호작용하는 콘솔 프로그램에서 유용합니다.

const readline = require('readline');

// createInterface 메서드로 인터페이스 생성
const rl = readline.createInterface({
    input: process.stdin,  // 사용자의 입력을 읽을 스트림
    output: process.stdout // 사용자에게 출력할 스트림
});

// 사용자에게 질문하고, 사용자의 입력을 처리하는 이벤트 핸들러 등록
rl.question('What is your name? ', (answer) => {
    console.log(`Hello, ${answer}!`);
    rl.close(); // 인터페이스 닫기
});

// 인터페이스가 닫힐 때의 이벤트 핸들러 등록
rl.on('close', () => {
    console.log('Goodbye!');
});

위 코드에서 rl.question은 사용자에게 질문을 출력하고, 사용자가 답을 입력하면 콜백 함수가 실행됩니다. rl.close()를 호출하여 인터페이스를 닫으면 프로그램이 종료됩니다.

이런 용도였군. 그래서 close 안에 콘솔을 입력해야 되는구나.
참 코딩은 배워도 배워도 새롭네

profile
총총

0개의 댓글