[C#] 기본 입출력, 변수

2024. 6. 17. 20:44컴퓨터 언어/C#

728x90
반응형

이 포스팅은 마이크로소프트 C# 강의를 바탕으로 요약한 정보임을 밝힙니다.

https://learn.microsoft.com/ko-kr/training/paths/get-started-c-sharp-part-1/

 

C#을 사용하여 첫 번째 코드 작성(C#로 시작, 파트 1) - Training

C#을 사용하여 간단한 애플리케이션을 빌드하는 데 필요한 기본 구문 및 사고 프로세스를 알아봅니다.

learn.microsoft.com

 

출력

1. Console.Write : 개행 없이 출력

2. Console.WriteLine : 출력 후 개행

Console.Write("hello world!");
Console.WriteLine(" My name is chulsoo");
Console.Write("Thank you!");

 

출력

hello world! My name is chulsoo
Thank you!

 

리터럴 출력

1. 123 : int

2. 123.4F : float

3. 123.4 : double

4. 123.4m : decimal

5. true : bool

6. false : bool 

7. "hello world" : string

8. 'h' : char

 

Console.WriteLine(123);
Console.WriteLine(123.4F);
Console.WriteLine(123.4);
Console.WriteLine(123.4m);
Console.WriteLine(true);
Console.WriteLine(false);
Console.WriteLine("hello world");
Console.WriteLine('h');

 

출력

123

123.4

123.4

123.4

True

False

hello world

h

 

변수

변수를 선언할 때는 앞에 자료형을 붙여줘야 한다.

 

int a = 123;
float b = 123.4F;
double c = 123.4;
decimal d = 123.4m;
bool e = true;
bool f = false;
string g = "hello";
char h = 'h';
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
Console.WriteLine(e);
Console.WriteLine(f);
Console.WriteLine(g);
Console.WriteLine(h);

 

문자열에는 홑따옴표가 아닌 쌍따옴표를 사용해야 한다.

 

출력

123
123.4
123.4
123.4
True
False
hello
h

 

변수에 자료형과 변수에 입력되는 값의 자료형은 동일해야 한다.

 

대신 자료형 var를 사용하면 유동적으로 자료형을 정할 수 있다.

 

그러나 var를 사용해서 특정한 자료형으로 초기화 했다면 다른 자료형으로 변경할 수는 없다.

 

var a = "hello world";
var b =123;
var c = 123.5F;
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);

 

출력

hello world
123
123.5

 

변수를 선언하면 반드시 초기화를 해야 한다.

 

이스케이프 시퀀스

1. \n : 개행

2. \t : 탭

Console.WriteLine("Hello!\nworld!");

 

출력

Hello!
world!
 
 
만약 백스페이스를 출력하고 싶다면 \\를 사용하거나 축자 문자열을 사용할 수 있다.
 
축자 문자열은 문자열 앞에 @를 붙이면 된다.
 
Console.WriteLine("C:\\practice");
Console.WriteLine(@"C:\practice");

 

출력

C:\practice
C:\practice
 
 

문자열 결합

문자열끼리는 덧셈 연산자로 합칠 수 있다.

string a = "hello ";
string b = "world!";
Console.WriteLine(a+b);

 

출력

hello world!

 

만약 중간에 정수가 들어간다면 정수를 문자열로 바꿔준다.

 

Console.WriteLine(a+1+b);

 

출력

hello 1world!

 

만약 중간에 연산을 하고 싶다면 괄호로 묶어준다.

 

Console.WriteLine(a+(1+2)+b);

 

출력

hello 3world!

728x90
반응형