배열

 

// 배열
int[] array1 = new int[5];       // 크기가 5인 int형 배열 선언
string[] array2 = new string[3]; // 크기가 3인 string형 배열 선언
int num = 0;

array1[0] = 1; // 배열 초기화 - 보통 for문 등 반복문 사용
array1[1] = 2;
array1[2] = 3;
array1[3] = 4;
array1[4] = 5;

// 배열 예제
num = array1[0];

int[] itemPrices = { 100, 200, 300, 400, 500 };
int totalPrice = 0;

for (int i = 0; i < itemPrices.Length; i++)
{
    totalPrice += itemPrices[i];
}

Console.WriteLine("총 아이템 가격: " + totalPrice + " gold");

 

배열 예제

// 게임캐릭터 능력치 만들기
int[] playerStats = new int[4]; // 플레이어의 공격력, 방어력, 체력, 스피드를 저장할 배열

Random rand = new Random(); // 능력치를 랜덤으로 생성하여 배열에 저장
for (int i = 0; i < playerStats.Length; i++)
{
    playerStats[i] = rand.Next(1, 11);
}

Console.WriteLine("플레이어의 공격력: " + playerStats[0]);
Console.WriteLine("플레이어의 방어력: " + playerStats[1]);
Console.WriteLine("플레이어의 체력: " + playerStats[2]);
Console.WriteLine("플레이어의 스피드: " + playerStats[3]);
// 학생들의 성적 평균 구하기
int[] scores = new int[5];  // 5명의 학생 성적을 저장할 배열

for (int i = 0; i < scores.Length; i++) // 성적 입력 받기
{
    Console.Write("학생 " + (i + 1) + "의 성적을 입력하세요: ");
    scores[i] = int.Parse(Console.ReadLine());
}

int sum = 0; // 성적 총합 계산
for (int i = 0; i < scores.Length; i++)
{
    sum += scores[i];
}

double average = (double)sum / scores.Length;
Console.WriteLine("성적 평균은 " + average + "입니다."); // 성적 평균 출력
// 배열을 활용한 숫자 맞추기 게임
Random random = new Random();  // 랜덤 객체 생성
int[] numbers = new int[3];  // 3개의 숫자를 저장할 배열

for (int i = 0; i < numbers.Length; i++) // 3개의 랜덤 숫자 생성하여 배열에 저장
{
    numbers[i] = random.Next(1, 10);
}

int attempt = 0;  // 시도 횟수 초기화
while (true)
{
    Console.Write("3개의 숫자를 입력하세요 (1~9): ");
    int[] guesses = new int[3];  // 사용자가 입력한 숫자를 저장할 배열

    for (int i = 0;i < guesses.Length; i++)
    {
        guesses[i] = int.Parse(Console.ReadLine());
    }

    int correct = 0; // 맞춘 숫자의 개수 초기화

    for (int i = 0; i < numbers.Length; i++) // 숫자 비교 및 맞춘 개수 계산

    {
        for (int j = 0; j < guesses.Length; j++)
        {
            if (numbers[i] == guesses[j])
            {
                correct++;
                break;
            }
        }
    }

    attempt++;  // 시도 횟수 증가
    Console.WriteLine("시도 #" + attempt + ": " + correct + "개의 숫자를 맞추셨습니다.");

    // 모든 숫자를 맞춘 경우 게임 종료
    if (correct == 3)
    {
        Console.WriteLine("축하합니다! 모든 숫자를 맞추셨습니다.");
        break;
    }
}

 

다차원 배열

  • 여러 개의 배열을 하나로 묶어 놓은 배열
  • 행과 열로 이루어진 표 형태와 같은 구조
  • 2차원, 3차원 등의 형태의 배열을 의미
  • C#에서는 다차원 배열을 선언할 때 각 차원의 크기를 지정하여 생성한다.
// 2차원 배열의 선언과 초기화
int[,] array3 = new int[2, 3];  // 2행 3열의 int형 2차원 배열 선언

// 다차원 배열 초기화
array3[0, 0] = 1;
array3[0, 1] = 2;
array3[0, 2] = 3;
array3[1, 0] = 4;
array3[1, 1] = 5;
array3[1, 2] = 6;

// 선언과 함께 초기화
int[,] array2D = new int[3, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };

 

3차원 이상은 잘 사용하지 않는다.

// 3차원 배열의 선언과 초기화
int[,,] array3D = new int[2, 3, 4] 
{
    { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } },
    { { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, { 21, 22, 23, 24 } }
};

 

다차원 배열 예제

int[,] map = new int[5, 5];
for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 5; j++)
    {
        map[i, j] = i + j;
    }
}

for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 5; j++)
    {
        Console.Write(map[i, j] + " ");
    }
    Console.WriteLine();
}
  • 다차원 배열을 활용하면 복잡한 데이터 구조를 효율적으로 관리할 수 있다.
  • 2차원 배열은 행과 열로 이루어진 데이터 구조를 다루기에 적합하다.
  • 3차원 배열은 면, 행, 열로 이루어진 데이터 구조를 다루기에 적합하다.
// 게임 맵 구현
int[,] map = new int[5, 5] 
{ 
    { 1, 1, 1, 1, 1 }, 
    { 1, 0, 0, 0, 1 }, 
    { 1, 0, 1, 0, 1 }, 
    { 1, 0, 0, 0, 1 }, 
    { 1, 1, 1, 1, 1 } 
};

for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 5; j++)
    {
        if (map[i, j] == 1)
        {
            Console.Write("■ ");
        }
        else
        {
            Console.Write("□ ");
        }
    }
    Console.WriteLine();
}

 

 

컬렉션

자료를 모아놓은 데이터 구조

  • 컬렉션은 배열과 비슷한 자료 구조
  • 배열과는 다르게 크기가 가변적
  • C#에서는 다양한 종류의 컬렉션을 제공
  • 사용하기 위해서는 System.Collections.Generic 네임스페이스를 추가

 

List(리스트)

동적 배열. List를 생성할 때 담을 자료형을 지정해야한다.

List<int> numbers = new List<int>(); // 빈 리스트 생성
numbers.Add(1); // 리스트에 데이터 추가
numbers.Add(2);
numbers.Add(3);
numbers.Remove(2); // 리스트에서 데이터 삭제

for (int i = 0; i < numbers.Count; i++) // 리스트 데이터 출력 - for문
{
    Console.WriteLine(numbers[i]);
}

foreach (int number in numbers) // 리스트 데이터 출력 - foreach문
{
    Console.WriteLine(number);
}

 

Dictionary(딕셔너리)

키와 값으로 구성된 데이터 저장. 중복된 키를 가질 수 없고, 키와 값의 쌍을 이룬다.

Dictionary<string, int> scores = new Dictionary<string, int>(); // 빈 딕셔너리 생성
scores.Add("Alice", 100); // 딕셔너리에 데이터 추가
scores.Add("Bob", 80);
scores.Add("Charlie", 90);
scores.Remove("Bob"); // 딕셔너리에서 데이터 삭제

foreach(KeyValuePair<string, int> pair in scores) // 딕셔너리 데이터 출력
{
    Console.WriteLine(pair.Key + ": " + pair.Value);
}

 

Stack

후입선출(LIFO) 구조를 가진 자료 구조

Stack<int> stack1 = new Stack<int>();  // int형 Stack 선언

stack1.Push(1); // Stack에 요소 추가
stack1.Push(2);
stack1.Push(3);

int value = stack1.Pop(); // Stack에서 요소 가져오기

 

Queue

선입선출(FIFO) 구조를 가진 자료 구조

Queue<int> queue1 = new Queue<int>(); // int형 Queue 선언

queue1.Enqueue(1); // Queue에 요소 추가
queue1.Enqueue(2);
queue1.Enqueue(3);

int value = queue1.Dequeue(); // Queue에서 요소 가져오기

 

HashSet

중복되지 않은 요소들로 이루어진 집합

HashSet<int> set1 = new HashSet<int>();  // int형 HashSet 선언

set1.Add(1); // HashSet에 요소 추가
set1.Add(2);
set1.Add(3);

foreach (int element in set1) // HashSet에서 요소 가져오기
{
    Console.WriteLine(element);
}

 

 

 

조건문

코드의 참과 거짓을 판단하여 실행한다.

 

조건문 기초

// if문 기초
int playerScore = 80;

if (playerScore >= 70)
{
    Console.WriteLine("플레이어의 점수는 70점 이상입니다. 합격입니다!");
}
Console.WriteLine("프로그램이 종료됩니다.");

// else문 기초
if (itemCount > 0)
{
    Console.WriteLine($"보유한 {itemName}의 수량: {itemCount}");
}
else
{
    Console.WriteLine($"보유한 {itemName}이 없습니다.");
}

if문과 else문은 하나의 쌍이며 else문은 생략 가능하다.

 

// else if문 실습
int score = 100;
string playerRank = "";

if (score >= 90)
{
    playerRank = "Diamond";
}
else if (score >= 80)
{
    playerRank = "Platinum";
}
else if (score >= 70)
{
    playerRank = "Gold";
}
else if (score >= 60)
{
    playerRank = "Silver";
}
else
{
    playerRank = "Bronze";
}

Console.WriteLine("플레이어 등급은 {0} 입니다.", playerRank);

 

// switch문
Console.WriteLine("게임을 시작합니다.");
Console.WriteLine("1: 전사 / 2: 마법사 / 3: 궁수");
Console.Write("직업을 선택하세요: ");
string job = Console.ReadLine();

switch (job)
{
    case "1":
        Console.WriteLine("전사를 선택하셨습니다.");
        break;
    case "2":
        Console.WriteLine("마법사를 선택하셨습니다.");
        break;
    case "3":
        Console.WriteLine("궁수를 선택하셨습니다.");
        break;
    default:
        Console.WriteLine("올바른 값을 입력해주세요.");
        break;
}

Console.WriteLine("게임을 종료합니다.");

 

 

// 중첩 조건문
int itemLevel = 3; // 아이템 레벨
string itemType = "Weapon"; // 아이템 종류

if (itemType == "Weapon")
{
    if (itemLevel == 1)
    {
        // 레벨 1 무기 효과
        Console.WriteLine("공격력이 10 증가했습니다.");
    }
    else if (itemLevel == 2)
    {
        // 레벨 2 무기 효과
        Console.WriteLine("공격력이 20 증가했습니다.");
    }
    else
    {
        // 그 외 무기 레벨
        Console.WriteLine("잘못된 아이템 레벨입니다.");
    }
}
else if (itemType == "Armor")
{
    if (itemLevel == 1)
    {
        // 레벨 1 방어구 효과
        Console.WriteLine("방어력이 10 증가했습니다.");
    }
    else if (itemLevel == 2)
    {
        // 레벨 2 방어구 효과
        Console.WriteLine("방어력이 20 증가했습니다.");
    }
    else
    {
        // 그 외 방어구 레벨
        Console.WriteLine("잘못된 아이템 레벨입니다.");
    }
}
else
{
    // 그 외 아이템 종류
    Console.WriteLine("잘못된 아이템 종류입니다.");
}

 

삼항 연산자

(조건식) ? 참일 경우 값 : 거짓일 경우 값;
int currentExp = 1200;
int requiredExp = 2000;

// 삼항 연산자
string result = (currentExp >= requiredExp) ? "레벨업 가능" : "레벨업 불가능";
Console.WriteLine(result);


// if else문
if (currentExp >= requiredExp)
{
    Console.WriteLine("레벨업 가능");
}
else
{
    Console.WriteLine("레벨업 불가능");
}

 

조건문 심화

// 홀수 / 짝수 구분하기 - if문
Console.Write("번호를 입력하세요: ");
int number = int.Parse(Console.ReadLine());

if (number % 2 == 0)
{
    Console.WriteLine("짝수입니다.");
}
else
{
    Console.WriteLine("홀수입니다.");
}


// 홀수 / 짝수 구분하기 - 삼항 연산자
Console.Write("번호를 입력하세요: ");
string result = (int.Parse(Console.ReadLine()) % 2 == 0) ? "짝수입니다." : "홀수입니다.";
Console.Write(result);
// 등급 출력 - switch문
int playerScore = 100;
string playerRank = "";

switch (playerScore / 10)
{
    case 10:
    case 9:
        playerRank = "Diamond";
        break;
    case 8:
        playerRank = "Platinum";
        break;
    case 7:
        playerRank = "Gold";
        break;
    case 6:
        playerRank = "Silver";
        break;
    default:
        playerRank = "Bronze";
        break;
}

Console.WriteLine("플레이어의 등급은 " + playerRank + "입니다.");
// 로그인 프로그램
string id = "myid";
string password = "mypassword";

Console.Write("아이디를 입력하세요: ");
string inputId = Console.ReadLine();
Console.Write("비밀번호를 입력하세요: ");
string inputPassword = Console.ReadLine();

if (inputId == id && inputPassword == password)
{
    Console.WriteLine("로그인 성공!");
}
else
{
    Console.WriteLine("로그인 실패...");
}
// 알파벳 판별 프로그램
Console.Write("문자를 입력하세요: ");
char input = Console.ReadLine()[0];

if (input >= 'a' && input <= 'z' || input >= 'A' && input <= 'Z')
{
    Console.WriteLine("알파벳입니다.");
}
else
{
    Console.WriteLine("알파벳이 아닙니다.");
}

// 알파벳 판별 프로그램 - 삼항 연산자
Console.Write("문자를 입력하세요: ");
char c = Console.ReadLine()[0];
string alp = (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') ? "알파벳입니다." : "알파벳이 아닙니다.";
Console.WriteLine(alp);

 

 

반복문

일련의 코드를 몇 번 반복하거나 조건에 해당할 때까지 반복을 도는 과정

 

반복문 기초

// for 문 기초
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(i);
}

int j = 0;
for (j = 0; j < 10; j++)
{
    Console.WriteLine(j);
}

 

// while문 기초
int k = 0;
while (k < 10)
{
    Console.WriteLine(k);
    k++;
}

int count = 0;
while (count < 10)
{
    Console.WriteLine("적을 처치했습니다! 남은 적 수: " + (10 - count - 1));
    count++;
}

Console.WriteLine("축하합니다! 게임에서 승리하셨습니다!");

for문은 명확한 회차나 데이터가 있을 때 사용하기 좋고 while문은 조건에 부합하는 반복을 돌릴 때 사용하기 좋다.

 

// for 문 vs while 문
int sum1 = 0;

for (int i = 1; i <= 5; i++)
{
    sum1 += i;
}

Console.WriteLine("1부터 5까지의 합은 " + sum1 + "입니다.");

int sum2 = 0;
int k = 1;

while (k <= 5)
{
    sum2 += k;
    k++;
}

Console.WriteLine("1부터 5까지의 합은 " + sum2 + "입니다.");
  • for 문은 반복 횟수를 직관적으로 알 수 있고, 반복 조건을 한 눈에 확인할 수 있어 가독성이 좋다.
  • while 문은 반복 조건에 따라 조건문의 실행 횟수가 유동적이며, 이에 따라 코드가 더 간결할 수 있다.
// do while문
int sum = 0;
int num;

do
{
    Console.Write("숫자를 입력하세요 (0 입력 시 종료): ");
    num = int.Parse(Console.ReadLine());
    sum += num;
} while (num != 0);

Console.WriteLine("합계: " + sum);

// for each문
string[] inventory = { "검", "방패", "활", "화살", "물약" };

foreach (string item in inventory)
{
    Console.WriteLine(item);
}

 

// 중첩 반복문 - 이차원 반복문
// 구구단 출력
for (int i = 2; i <= 9; i++)
{
    for (int j = 1; j <= 9; j++)
    {
        Console.WriteLine(i + " x " + j + " = " + (i * j));
    }
}

// 구구단 가로
for (int i = 2; i <= 9; i++)
{
    for (int j = 1; j <= 9; j++)
    {
        Console.Write(i + " x " + j + " = " + (i * j) + "\t");
    }
    Console.WriteLine();
}

// 구구단 세로
for (int i = 1; i <= 9; i++)
{
    for (int j = 2; j <= 9; j++)
    {
        Console.Write(j + " x " + i + " = " + (i * j) + "\t");
    }
    Console.WriteLine();
}

 

Break & Continue

// Break & Continue
for (int i = 1; i <= 10; i++)
{
    if (i % 3 == 0)
    {
        continue; // 3의 배수인 경우 다음 숫자로 넘어감
    }

    Console.WriteLine(i);
    if (i == 7)
    {
        break; // 7이 출력된 이후에는 반복문을 빠져나감
    }
}

// Break & Continue 예제
int sum = 0;

while (true)
{
    Console.Write("숫자를 입력하세요: ");
    int input = int.Parse(Console.ReadLine());

    if (input == 0)
    {
        Console.WriteLine("프로그램을 종료합니다.");
        break;
    }

    if (input < 0)
    {
        Console.WriteLine("음수는 무시합니다.");
        continue;
    }

    sum += input;
    Console.WriteLine("현재까지의 합: " + sum);
}

Console.WriteLine("합계: " + sum);

 

반복문 심화

// 가위바위보
string[] choices = { "가위", "바위", "보" };
string playerChoice = "";
string computerChoice = "";

while (true)
{
    computerChoice = choices[new Random().Next(0, 3)];
    Console.Write("가위, 바위, 보 중 하나를 선택하세요: ");
    playerChoice = Console.ReadLine();

    Console.WriteLine("컴퓨터: " + computerChoice);

    if (playerChoice == computerChoice)
    {
        Console.WriteLine("비겼습니다!");
    }
    else if ((playerChoice == "가위" && computerChoice == "보") ||
             (playerChoice == "바위" && computerChoice == "가위") ||
             (playerChoice == "보" && computerChoice == "바위"))
    {
        Console.WriteLine("플레이어 승리!");
    }
    else if ((playerChoice == "가위" && computerChoice == "바위") ||
             (playerChoice == "바위" && computerChoice == "보") ||
             (playerChoice == "보" && computerChoice == "가위"))
    {
        Console.WriteLine("컴퓨터 승리!");
    }
    else
    {
        Console.WriteLine("가위, 바위, 보 중 하나를 선택하세요! ");
    }
}

// 숫자 맞추기
int targetNumber = new Random().Next(1, 101); ;
int guess = 0;
int count = 0;

Console.WriteLine("1부터 100 사이의 숫자를 맞춰보세요.");

while (guess != targetNumber)
{
    Console.Write("추측한 숫자를 입력하세요: ");
    guess = int.Parse(Console.ReadLine());
    count++;

    if (guess < targetNumber)
    {
        Console.WriteLine("좀 더 큰 숫자를 입력하세요.");
    }
    else if (guess > targetNumber)
    {
        Console.WriteLine("좀 더 작은 숫자를 입력하세요.");
    }
    else
    {
        Console.WriteLine("축하합니다! 숫자를 맞추셨습니다.");
        Console.WriteLine("시도한 횟수: " + count);
    }
}
//출력
// 줄바꿈
{
    Console.WriteLine("Hello World!");
    Console.WriteLine("My Name is Ju");

    Console.WriteLine(10);
    Console.WriteLine(3.141592);
    Console.WriteLine(3 + 3);
}

// 한줄 출력
{
    Console.Write("Hello! ");
    Console.Write("We are Learning ");
    Console.WriteLine("at TeamSparta");
}

// 입력
{
    Console.Write("Enter your name: ");
    string name = Console.ReadLine();
    Console.WriteLine("Hello, {0}!", name);
}


// Split 함수 문자열 나누기 + 형변환
{
    Console.Write("Enter two numbers: ");
    string input = Console.ReadLine();    // "10 20"과 같은 문자열을 입력받음
    // { "10", "20" }
    string[] numbers = input.Split(' ');  // 문자열을 공백으로 구분하여 배열로 만듦
    int num1 = int.Parse(numbers[0]);     // 첫 번째 값을 정수로 변환하여 저장
    int num2 = int.Parse(numbers[1]);     // 두 번째 값을 정수로 변환하여 저장

    int sum = num1 + num2;                // 두 수를 더하여 결과를 계산

    Console.WriteLine("The sum of {0} and {1} is {2}.", num1, num2, sum);
}


// var 키워드
{
    var num = 10;         // int 자료형으로 결정됨
    var name = "kero";   // string 자료형으로 결정됨
    var pi = 3.141592;    // double 자료형으로 결정됨
}


// 산술 연산자
{
    int num1 = 20, num2 = 10;

    Console.WriteLine(num1 + num2);
    Console.WriteLine(num1 - num2);
    Console.WriteLine(num1 / num2);
    Console.WriteLine(num1 * num2);
    Console.WriteLine(num1 % num2);
}

// 관계 연산자
{
    int num1 = 20, num2 = 10;

    Console.WriteLine(num1 == num2);
    Console.WriteLine(num1 != num2);
    Console.WriteLine(num1 > num2);
    Console.WriteLine(num1 < num2);
    Console.WriteLine(num1 >= num2);
    Console.WriteLine(num1 <= num2);
}

// 논리 연산자
{
    int num3 = 15; 
    0 <= num3 <= 20

    Console.WriteLine(0 <= num3 && num3 <= 20); // 0과 20 사이에 포함되면
    Console.WriteLine(0 > num3 || num3 > 20); // 0 ~ 20 사이에 포함되지 않으면

    Console.WriteLine(!(0 <= num3 && num3 <= 20)); // 0과 20 사이에 포함되어있지 않으면
}


// 비트 연산자
{
    int a = 0b1100; // 12 (2진수)
    int b = 0b1010; // 10 (2진수)

    int and = a & b; // 0b1000 (8) 두 비트 값이 모두 1일 때 1을 반환
    int or = a | b; // 0b1110 (14) 두 비트 값 중 하나라도 1일 때 1을 반환
    int xor = a ^ b; // 0b0110 (6) 두 비트 값이 서로 다를 때 1을 반환
    int not = a; // 0b0011 비트 값의 보수(complement)를 반환

    int c = 0b1011; // 11 (2진수)
    int leftShift = c << 2; // 0b101100 (44) 비트를 왼쪽으로 이동
    int rightShift = c >> 1; // 0b0101 (5) 비트를 오른쪽으로 이동

    int d = 0b1100; // 12 (2진수)
    int bit3 = (d >> 2) & 0b1; // 0 (3번째 비트)
    d |= 0b1000; // 0b1100 | 0b1000 = 0b1100 (12)
}

// 연산자 우선순위
{
    1.괄호(): 괄호로 감싸진 부분은 가장 높은 우선순위로 먼저 계산됩니다.
    2.단항 연산자: 단항 연산자들(++, --, +, -, !등)은 괄호 다음으로 높은 우선순위를 가집니다.
    3.산술 연산자: 산술 연산자들(*, /, %, +, -)은 단항 연산자보다 우선순위가 낮습니다.
    4.시프트 연산자: 시프트 연산자(<<, >>)는 산술 연산자보다 우선순위가 낮습니다.
    5.관계 연산자: 관계 연산자들(<, >, <=, >=, ==, !=)는 시프트 연산자보다 우선순위가 낮습니다.
    6.논리 연산자: 논리 연산자들(&&, ||)는 관계 연산자보다 우선순위가 낮습니다.
    7.할당 연산자: 할당 연산자들(=, +=, -=, *=, /= 등)는 논리 연산자보다 우선순위가 낮습니다.
}


// 문자열 처리 기능 메서드
// 문자열 생성
{
    string str1 = "Hello, World!"; // 리터럴 문자열 사용
    string str2 = new string('H', 5); // 문자 'H'를 5개로 구성된 문자열 생성
}

// 연결 - 포멧팅을 더 자주 사용한다
{
    string str1 = "Hello";
    string str2 = "World";
    string str3 = str1 + " " + str2;
}

// 분할
{
    string str = "Hello, World!";
    string[] words = str.Split(','); // str 문자열을 쉼표(,)로 구분
}

// 검색
{
    string str = "Hello, World!";
    int index = str.IndexOf("World"); // str 문자열에서 "World" 문자열의 첫 번째 인덱스를 찾아 index 변수에 저장
}

// 대체
{
    string str = "Hello, World!";
    string newStr = str.Replace("World", "Universe"); // str 문자열에서 "World" 문자열을 "Universe" 문자열로 대체한 새로운 문자열 newStr을 생성
}

// 변환
{
    string str = "123";
    int num = int.Parse(str);
}
{
    int num = 123;
    string str = num.ToString();
}

// 비교
{
    string str1 = "Apple";
    string str2 = "Banana";
    int compare = string.Compare(str1, str2); // 사전식 비교. str1이 str2보다 작으면 음수, 크면 양수, 같으면 0이 나온다.
}

// 포멧팅
// 형식화
{
    string name = "John";
    int age = 30;
    string message = string.Format("My name is {0} and I'm {1} years old.", name, age);
}
//보간
{
    string name = "John";
    int age = 30;
    string message = $"My name is {name} and I'm {age} years old.";
}

 

 

Parse랑 Convert의 차이

파싱 실패했을 때, Parse는 FormatException을 내보내고 Convert는 기본값(int같은 경우 0)을 내보낸다.즉, Parse는 예외처리가 되고 Convert는 안된다. 데이터가 항상 명확하고 원하는 값이라면 Parse를 사용하고 불확실할 때는 Covert를 사용한다.

오늘의 계획

1. 마지막 수정 및 점검

2. 발표

3. 개인 알고리즘 공부

 

  • 발표

전날에 발표 대본은 써놨지만 발표에 대한 경험이 거의 없고 열심히 팀원들과 준비한 게임을 내 발표로 망칠까봐 걱정이 많이 됐다. 하지만 이때 아니면 언제 발표를 연습해보겠어! 라는 생각과 팀원분들의 격려로 ppt자료와 대본을 한 번 더 체크했다.

미니프로젝트이지만 처음으로 팀원들과 협동하며 하나의 게임을 완성한 경험은 아쉬우면서도 뿌듯했다. 시간이 좀 더 있었다면 구현하면 좋았을텐데 싶은 부분과 발표 때 긴장해서 말을 제대로 못한게 아쉽기도 했지만 새로운 경험이라 재밌었다.

 

  • 알고리즘 문제 풀이

C# 코딩테스트 알고리즘 코드타카 문제를 풀던 중, 두 수의 나눗셈 부분에서 Convert 함수와 (double), (int) 등의 형변환 방식의 차이점이 무엇일까 궁금증이 생겼다. Convert 함수는 String처럼 숫자형이 아닌 자료형도 변환시켜줄 수 있지만 (double), (int) 등의 형변환은 숫자형끼리만 변환시킬 수 있었다.

 

나의 첫 코드는 이랬는데

public class Solution {
    public int solution(int num1, int num2) {
        double answer = Convert.ToDouble(num1 / num2 * 1000);
        return Convert.ToInt32(answer);
    }
}

 

int형의 num1과 num2가 계산되어 정수로 반환되기 때문에 소수점을 반환할 수 없었다.

 

고로 이렇게 num1을 double형으로 변환시켜서 int형과 계산해도 더 상위의 형식인 double형으로 나오도록 했다.

public class Solution {
    public int solution(int num1, int num2) {
        double answer = Convert.ToDouble(num1) / num2 * 1000;
        return Convert.ToInt32(answer);
    }
}
public class Solution {
    public int solution(int num1, int num2) {
        double answer = (double)num1 / num2 * 1000;
        return (int)answer;
    }
}

 

 

+ C#은 파이썬과 달리 중첩 비교연산자 사용이 안된다는 사실을 알게 되었다.

틀린 예)

if (0 < angle < 90)

 

올바른 예)

if (0 < angle && angle < 90)

 

 

+ Recent posts