have to do_yeon
[C#] 2. 변수 본문
문자열 연결
기본적인 출력문을 통하여 출력 가능하다.
중간에 변수를 출력해야 할 경우, +를 통하여 문자열 간의 합으로 나타낼 수 있다.
변수를 출력할 때, 문자열 안에 중괄호를 활용한 배열 형태{i}로 나타내면, 문자열 뒤에 쉼표를 통하여 변수명을 입력하면 배열 순서 0부터 차례대로 해당 자리에 출력된다.
또는, 출력해야 할 문자열 앞에 $를 붙이고, 문자열 안에 중괄호를 활용하여 변수명을 삽입하면 변수의 값을 출력할 수 있다.
using System;
class StringInterpolation
{
static void Main()
{
// variable
string name1 = "C#";
string name2 = "Unity";
// String interpolation
Console.WriteLine("Hello Unity");
Console.WriteLine("Hello" + " " + name1);
Console.WriteLine("Hello {0}, {1}", name1, name2);
Console.WriteLine($"Hello {name1}, {name2}");
}
}
변수 선언, 할당과 참조
변수를 활용하기 위해서는 선언과 할당이 필요하다.
자료형 변수명; 의 형태로 선언하며 = 를 통하여 값을 할당한다.
자료형 변수명 = 값; 의 형태로 선언과 동시에 할당이 가능하다.
using System;
class Variable
{
static void Main()
{
// Variable 선언
int a, b;
string name = "rose";
// 변수 할당
a = 100;
b = 200;
// 변수 참조
Console.WriteLine($"a = {a}, b = {b}"); // string interpolation
Console.WriteLine($"a + b = {a + b}");
Console.WriteLine(name);
}
}
자료형 - 정수형
정수를 나타내는 자료형은 여러가지가 있는데, 그 각각은 크기와 부호가 모두 다르다.
상황에 알맞게 사용하여야 한다.
해당 자료형의 범위를 벗어나는 정수를 활용할 경우 오류가 난다.
using System;
class NumericVariable
{
static void Main()
{
int a = 256; // 선언 할당, 4 byte, 32 bit
byte b = 255; // 1 byte, 8 bit => 0~255
short c = 256; // 2 byte
long d = 255555555555555555;
Console.WriteLine($"int a = {a}");
Console.WriteLine($"byte b = {b}");
Console.WriteLine($"long d = {d}");
// Memory size
Console.WriteLine($"max short = {short.MaxValue}");
Console.WriteLine($"max short = {short.MinValue}");
Console.WriteLine($"max int = {Int32.MaxValue}");
Console.WriteLine($"max int = {Int32.MinValue}");
int signedbyteMin = sbyte.MinValue;
int signedbyteMax = sbyte.MaxValue;
Console.WriteLine("signed byte min = {0}, signed byte maxd = {1}", signedbyteMin, signedbyteMax);
}
}
자료형 - 실수형
정수 자료형과 같이 각각의 자료형은 크기가 모두 다르다.
float과 decimal 자료형의 변수에 실수를 할당할 경우 숫자 뒤에 각각 f와 m을 붙여야 해당 자료형으로 인식한다.
decimal의 경우 float, double과 다르게 부동소숫점 방식을 사용한다.
고정소숫점 방식의 경우 미세한 오류가 있다.
이 오류는 중요한 작업에 있어서 문제가 생길 수 있기 때문에 그러한 부분에 활용하기 위한 decimal이라는 자료형이 등장하게 되었다.
sing System;
class FloatVariable
{
static void Main()
{
// 실수형
float floatValue = 3.141592f; // 부동소숫점
double doubleValue = 3.141592; // 부동소숫점
decimal decimalValue = 3.141592m; // 고정소숫점
Console.WriteLine($"float value = {floatValue}");
Console.WriteLine($"double value = {doubleValue}");
Console.WriteLine($"decimal value = {decimalValue}");
//
double f1 = 0.1;
double f2 = 0.2;
Console.WriteLine($"f1 + f2 = {f1 + f2}"); // f1 + f2 = 0.30000000000000004 오차가 생김
Console.WriteLine();
// 돈, 인공위성과 같은 정교한 계산이 필요한 경우 오차를 없애기 위해서 필요함
decimal d1 = 0.1m;
decimal d2 = 0.2m;
Console.WriteLine($"d1 + d2 = {d1 + d2}"); // d1 + d2 = 0.3
}
}
자료형 - 문자형
char과 string은 둘 다 문자에 관한 자료형이다.
char의 경우 한 문자를 값으로 받고, string은 문자열을 값으로 받는다.
그런데 string의 경우 입력될 값의 크기를 제한할 수 없으므로 참조 형식으로 사용된다.
따라서 배열 형식이므로 null값이 들어올 여지가 있음을 고려해야 한다.
string은 char의 배열이라고 생각하면 되므로 실제로 배열처럼 활용할 수 있다.
bool은 true(1), false(0) 두 값만을 가지는 자료형이다.
using System;
// 값형식
class CharStringBool
{
static void Main()
{
// char
char score = 'A';
char score_ko = '수';
Console.WriteLine($"Score = {score}");
Console.WriteLine($"Score = {score_ko}");
// String
string greeting = "Hello World"; // 문자열, 참조 형식의 자료형
string greeting_ko = "안녕하세요.";
Console.WriteLine($"{greeting}\\n{greeting_ko}");
Console.WriteLine(greeting_ko[0]); // 안
// bool
bool answer = true;
string answer_String = "True";
Console.WriteLine(answer);
Console.WriteLine(answer_String);
}
}
- 값 형식 int a = 10 일 때, int라는 자료형 자체를 판단하여 그 자료형에 맞는 메모리 할당. 데이터를 스택에 저장
- 참조 형식 string name = “doyeon” 일 때, 메모리(8 byte) 할당 후 데이터를 힙에 저장하고 그 주소를 스택으로 불러옴. 값의 크기가 유동적이기 때문. null 값이 들어올 경우를 고려하여 값을 입력받을 때 string? 변수명 = Console.ReadLine(); 으로 사용하는 경우가 많다.
형변환
Convert.~~ 를 활용하여 자료형을 변환할 수 있다.
주로 string 형을 int나 char로 변환할 때 사용한다.
// 10_TypeConvert
using System;
class TypeConvert
{
static void Main()
{
int a = 123456; //
long b = a; // implicit type change
byte c = (byte)a; // explicit type change
Console.WriteLine($"a type = {a.GetType()}");
Console.WriteLine($"b type = {b.GetType()}");
Console.WriteLine($"c type = {c.GetType()}, c = {c}");
char ch = 'c';
Console.WriteLine(ch);
Console.WriteLine(ch.GetType());
// 형변환
Console.WriteLine("Enter the number");
string? inputNumber = Console.ReadLine();
int inputInt = Convert.ToInt32(inputNumber);
//double inputDouble = Convert.ToDouble(inputNumber);
Console.WriteLine($"{inputInt + 10}");
}
}
암시적 형식 지역 변수
var 키워드를 사용하면 지역 변수를 선언할 때 컴파일러가 초기화 식에서 변수의 형식을 유추하도록 할 수 있다.
값에 따라 자동으로 자료형이 부여된다.
// 12_VarType
using System;
class VarType
{
static void Main()
{
var age = 23; // 자동으로 알맞은 자료형을 할당해줌
Console.WriteLine($"age type = {age.GetType()}"); // age type = System.Int32
var temperature = 15.5; // float, double
Console.WriteLine($"temperature type = {temperature.GetType()}"); // temperature type = System.Double
var weather = "clear";
Console.WriteLine($"weather type = {weather.GetType()}"); // weather type = System.String
}
}
'C# > Basic (C#)' 카테고리의 다른 글
[C#] 1. 기본 입출력 (0) | 2024.02.16 |
---|---|
0. C# 을 시작하며 (0) | 2024.02.16 |