[DAY3] 변수 선언(var), 변수 형식과 활용

m1njae·2022년 1월 5일
0

22 Basic Challenge

목록 보기
3/25
post-thumbnail

데이터를 어떻게 처리할 것인가? 라고 하는 것은 우리가 컴퓨터를 사용하는 가장 중요한 이유이다. 프로그래밍을 배우는 데 있어서 알아야 할 것은 어떠한 데이터가 있는지 그리고 각각의 데이터는 어떻게 처리하는지, 즉 데이터의 종류와 그것을 처리하는 방법일 것이다.

console

Javascript에는 console이라는 객체가 존재한다. console은 디버깅을 위해 존재하는 객체로, console의 함수를 이용하면 크롬 개발자도구의 콘솔창에 여러 정보를 출력할 수 있다.

  • console.log()는 가장 일반적으로 사용하는 함수로 자바스크립트 객체를 콘솔창에 출력하는 함수이다.
  • 매개변수로 전달된 값을 출력하며 요소를 HTML과 같은 트리 구조로 출력한다.

Javascript - 변수(variable)

var a = 1;
console.log(a);
a = 2;
console.log(a);
실행결과
1
2
  • 변수는 쓰이는 수식에 따라서 변하는 값을 말한다.

  • =은 대입 연산자로서 오른쪽에 있는 값을 왼쪽에 있는 변수에 대입해서 변수의 값을 오른쪽 값과 동일하게 해주는 역할을 한다.

  • 변수를 생성할 때 var를 작성해주는 것이 좋은 습관이며, 변수를 지정한 후, 변수의 값을 수정할 때는 var을 작성하지 않아도 된다.

  • var 변수 선언 이외에도 letconst라는 변수 선언 방식이 있다. 간략하게 소개하자면,
    - let변수 재선언이 불가능하지만 변수 재할당이 가능하다.
    -const는 변수 재선언, 변수 재할당 모두 불가능하다.
    - 자세한 내용은 링크를 참고

Javascript - 변수의 활용

console.log('JavaScript (/ˈdʒɑːvəˌskrɪpt/[6]), often abbreviated as JS, is a high-level, dynamic, weakly typed, prototype-based, multi-paradigm, and interpreted programming language. Alongside HTML and CSS, JavaScript is one of the three core technologies of World Wide Web content production. It is used to make webpages interactive and provide online programs, including video games. The majority of websites employ it, and all modern web browsers support it without the need for plug-ins by means of a built-in JavaScript engine. Each of the many JavaScript engines represent a different implementation of JavaScript, all based on the ECMAScript specification, with some engines not supporting the spec fully, and with many engines supporting additional features beyond ECMA.');

이처럼 혹은 이보다 더 긴 문자열과 긴 숫자를 코드로 작성한다고 상상해보자

그럼 코드를 확인해보았을 때, 어떤 데이터를 가지고 있는지 바로 알기에는 확실히 어려울 것이다. 이러한 어려움을 해소시켜줄 수 있는 도구가 바로 변수인 것이다. 변수에 여러가지 의미가 있지만 그 중의 하나는 바로 데이터의 이름을 붙인다는 것이다.

var explanation = 'JavaScript (/ˈdʒɑːvəˌskrɪpt/[6]), often abbreviated as JS, is a high-level, dynamic, weakly typed, prototype-based, multi-paradigm, and interpreted programming language. Alongside HTML and CSS, JavaScript is one of the three core technologies of World Wide Web content production. It is used to make webpages interactive and provide online programs, including video games. The majority of websites employ it, and all modern web browsers support it without the need for plug-ins by means of a built-in JavaScript engine. Each of the many JavaScript engines represent a different implementation of JavaScript, all based on the ECMAScript specification, with some engines not supporting the spec fully, and with many engines supporting additional features beyond ECMA.';
console.log(explanation);

결과적으로 화면에 출력되는 똑같지만 변수를 지정함으로써 코드의 가독성이 높아진다는 것을 알 수 있다. 변수의 이름을 붙여서 이 데이터의 내용은 무엇인가를 설명하고 있는 것이구나를 추론할 수 있고 의미하는 것의 범위를 좁힐 수 있게 되는 것이다. 또한, 이러한 기능들을 통해서 변수는 중복을 제거할 수 있으며 이것은 좋은 코드를 작성하는데 많은 도움을 줄 것이다.

백준 관련 문제 풀이

백준에서 javascript를 활용해서 입출력 알고리즘 문제를 풀려면 다음과 같은 과정을 거쳐야 한다고 한다.

// node.js의 file system 모듈을 불러온다.
var fs = require('fs'); 

// fs모듈의 readFileSync 함수를 통해 동기적으로 해당 경로의 파일 전체를 읽어들인다.
// 백준에서는 '/dev/stdin' 경로에 테스트 케이스 파일이 있다.
// 읽어드린 정보는 toString()함수를 통해 문자열로 변환하여야 사용할 수 있다.
// 입력 받은 문자열을 split() 함수를 통해 배열화한다. (split(' '), split('\n') 등)
// 예) 2 3 입력시, inputData = ['2', '3']
var inputData1 = fs.readFileSync('/dev/stdin').toString().split(' ');

// options으로 인코딩을 string 자료형으로 넘기는 경우, toString을 할 필요없이 문자열 반환
var inputData2 = fs.readFileSync(0, 'utf8').split(' ');

블로그를 참고했다.
백준에서 입출력과 사칙연산 문제를 풀어보았다. 문제들을 푸면서 필요했던 부분들은 구글링하면서 찾아보았다.

  • require()는 외부 모듈을 가져오는데 필요한 메서드이다.
  • toString()은 숫자를 문자열로 바꿔주는 함수이다.
  • readFileSync은 파일을 읽는 동기적 함수이다.
  • parseInt()는 문자열을 정수로 바꿔주는 함수이다.

오답 정리

10869번 사칙연산

내가 작성했던 오류 코드

var fs = require('fs');
var inputData = fs.readFileSync('/dev/stdin').toString().split(' ');

var a = parseInt(inputData[0]);
var b = parseInt(inputData[1]);

console.log(a+b);
console.log(a-b);
console.log(a*b);
console.log(a/b); 	//오류 부분
console.log(a%b);

오류 부분은 console.log(a/b);이었다. 단순히 a를 b로 나누게 된다면 소수점 이하로도 계속 나오게 된다. 7을 3으로 나누게 된다면 2.333333...이기 때문에 예제 출력과 같은 결과가 되려면 소수점을 처리해주어야 했다. 따라서 소수점 이하를 버려주는 함수인 Math.floor()를 이용해서 문제를 해결 할 수 있었다.

2588 곱셈

내가 작성했던 오류 코드

var fs = require('fs');
var inputData = fs.readFileSync('/dev/stdin').toString().split(' ');	//오류부분

var a = parseInt(inputData[0]);
var b = parseInt(inputData[1]);

var num1 = b % 10;
var num2 = Math.floor((b % 100) / 10);
var num3 = Math.floor(b / 100);

console.log(a * num1);
console.log(a * num2);
console.log(a * num3);
console.log(a * b);

오류 부분은 fs.readFileSync('/dev/stdin').toString().split(' '); 이었다. 예제 입력시에 받은 형태가 472 \n 385 이기에 split(' ')사용이 오류였다. 따라서 split('\n')로 수정 후 문제를 해결할 수 있었다.

느낀 점

공부를 진행하면서 시간이 오래 걸리기는 했지만 스스로 필요한 부분과 모르는 것을 찾아 해결한다는 점에서 고무적이었다. 다만 아쉬웠던 점은 디테일한 부분을 잡아내지 못했다는 점이었다. 계속해서 챌린지를 진행하면서 보완할 수 있도록 노력해야겠다.

profile
할 수 있는 것부터 차근차근, 항해자의 공부 기록공간

0개의 댓글