C++ 알고리즘 기초3 -변수와 자료형 기본-

1. 변수와 자료형

 

변수를 선언하는 것은 파이썬과 마찬가지로 a = 5; 처럼 간단하게 가능

 

하지만 C++에서는 자바처럼 변수의 적절한 자료형(type)을 선언해줘야한다.

 

int a;
a = 5;
cout << a;

 

5가 정수 자료형 int에 해당하여, a 변수를 int로 선언하고 5를 a에 대입해주었다.

 

C++에서 자주 쓰는 자료형은...

 

정수: int, long long

 

실수: double

 

문자: char

 

문자열: string

 

정수형과 실수형에 해당하는 변수들끼리는 사칙연산이 당연히 가능하다.

 

#include <iostream>
using namespace std;

int main() {
    
    int a = 5;
    int b = 9;
    int c = a+b;
    
    cout << "c = " << c;
    
    return 0;
}

c = 14

 

2개 이상의 변수를 선언할때, int a = 5, b = 9;와 같이 한 줄에 선언 가능하다

 

#include <iostream>
using namespace std;

int main() {
    
    int a = 5, b = 9;
    int c = a+b;
    cout << "c = " << c;
    
    return 0;
}

 

C++에서는 자바와는 다르게 파이썬처럼 변수나 함수명을 지을때, 언더바로 여러단어를 연결하는 것이 보통

 

make_prime, get_numbers

 

2. 연습문제

 

"97 - 13 = 84"를 출력하기

 

#include <iostream>
using namespace std;

int main() {
    // 여기에 코드를 작성해주세요.

    int a = 97, b = 13;

    cout << a << " - " << b << " = " << a-b;
    
    return 0;
}
97 - 13 = 84

 

첫번째 줄에는 3, 두번째 줄에는 'C'를 출력하기

 

#include <iostream>
using namespace std;

int main() {
    // 여기에 코드를 작성해주세요.

    int a = 3;
    char b = 'C';

    cout << a << endl << b;
    return 0;
}

 

3. string

 

C++에서 문자열 자료형을 사용하고 싶으면 헤더에 #include <string>을 포함시켜줘야함

 

근데 안써도 에러 안나는것 같은데?? 자세히 알아봐야할듯..

 

#include <iostream>
#include <string>
using namespace std;

int main() {
    
    int a = 5;
    cout << "A is " << a << endl;
    
    string b = "apple";
    cout << "B is " << b << endl;
    
    cout << "A is " << a << " and B is " << b;
    
    return 0;
}
A is 5
B is apple
A is 5 and B is apple

 

TAGS.

Comments