본문 바로가기

W3 Schools C, C++

02.변수 선언

728x90
반응형

C++ Variables (w3schools.com)

 

C++ Variables

C++ Variables C++ Variables Variables are containers for storing data values. In C++, there are different types of variables (defined with different keywords), for example: int - stores integers (whole numbers), without decimals, such as 123 or -123 double

www.w3schools.com


C++

#include <iostream>
using namespace std;

int main() {
	int myNum = 5;
	double myFloatNum = 5.99;
	char myLetter = 'D';
	string myText = "Hello";
	
	cout << "myNum : " << myNum << endl;
	cout << "myFloatNum : " << myFloatNum << endl;
	cout << "myLetterm : " << myLetter << endl;
	cout << "myTextm : " << myText << endl;	
}

 

 


C

#include <stdio.h>

int main(){
	int myNum = 5;
	double myFloatNum = 5.99;
	char myLetter = 'D';
	char myText[10] = "Hello";
	
	printf("myNum : %d\n", myNum);
	printf("myFloatNum : %f\n", myFloatNum);
	printf("myLetter : %c\n", myLetter);
	printf("myText : %s\n", myText);
}

 

 

변수 선언 - int, double, char, string이다.

C언어에는 string 변수라는건 없고, 위처럼 char의 범위를 늘려서 하는 방식으로 선언해야한다. 근데 생각해보니 있었던것 같기도한데 기억 안나서 그냥 저렇게 했다.

그리고 변수를 출력하는 방식도 다른데, C++ (및 그냥 다른 평범한 프로그래밍 언어들)은 자신이 선언한 변수명만 치면 그 값이 출력되지만, C언어는 각 타입에 맞게 %d, %f 등등을 쳐주어야하고, 출력 문법도 조금 불편하다.

 

  C C++
출력 문구 작성 방식 int a=1; char b='b';
printf("숫자 a와 문자 b : %d, %c", a, b) cout << "숫자 a와 문자 b : " << a << ", " << b
숫자 a와 문자 b : 1, b

 

 

728x90
반응형

'W3 Schools C, C++' 카테고리의 다른 글

04.연산자  (0) 2021.05.28
03.입출력  (0) 2021.05.28
01.Hello World  (0) 2021.05.26
W3 스쿨의 C, C++ 따라하기  (0) 2021.05.25