오늘의 학습 키워드
1. 자료형
2. 연산자
3. For, While, If 문
4. 구조체

Before Study
이제 슬슬 내가 공부했던 것들이 나오는구나.... 오늘은 공부보다는 예제 위주로 학습 해봐야지. 그리고 예제를 내가 얼마나 발전 시킬수있을지도 해봐야겠다.
Console.WriteLine 과 Console.Write에 관해 배웠는데
C는 printf 한다음에 그냥 \n을 쓰는것으로 줄바꿈을 했는데 C++ 에서는 WriteLine이라는 코드라는걸 보고 놀랬다.
그리고나서 그 다음 나오는 이스케이프 시퀀스 라는것들이 내가 아는 명령어들이구나... 라는걸 다시금 깨닫는 시간이였다.
항상 명령어 쓰다가 ctrl + space 라는 부분에 대해서 오...라는 감탄사를 내면서 '이런것도있구나 ㅎㅎ 써먹어야지' 싶었다.
자료형에 대해서는 솔직히 쓰는 자료형은 byte,int,float, double,char, bool 밖에 쓰는것이 없다고 생각했는데 세부적으로 들어갔는데 더 자세한것들이 있었다. 아래는 그 예시이다.
자료형 .NET 데이타 타입 크기 (바이트) 범위
| sbyte | System.SByte | 1 | -128 ~ 127 |
| byte | System.Byte | 1 | 0 ~ 255 |
| short | System.Int16 | 2 | -32,768 ~ 32,767 |
| ushort | System.UInt16 | 2 | 0 ~ 65,535 |
| int | System.Int32 | 4 | -2,147,483,648 ~ 2,147,483,647 |
| uint | System.UInt32 | 4 | 0 ~ 4,294,967,295 |
| long | System.Int64 | 8 | -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 |
| ulong | System.UInt64 | 8 | 0 ~ 18,446,744,073,709,551,615 |
| float | System.Single | 4 | ±1.5 × 10^-45 ~ ±3.4 × 10^38 |
| double | System.Double | 8 | ±5.0 × 10^-324 ~ ±1.7 × 10^308 |
| decimal | System.Decimal | 16 | ±1.0 × 10^-28 ~ ±7.9 × 10^28 |
| char | System.Char | 2 | 유니코드 문자 |
| string | System.String | 유니코드 문자열 | |
| bool | System.Boolean | 1 | true 또는 false |
int num 1 , num 2, num 3 = 10이라는건
num1,num2,num3 에 10이라는 값이 아니라,
num 1과 num2 는 선언만 된것이고 num3 의값에 10이 입력된거라고해서 음...? 이라고했다.
자바에서는 그냥 저렇게해도 됐었던것같은데...
변수 초기화 할떄 항상 조심해야겟다.
제일 좋은 예시는
int num1, num2, num3;
num1 = num2 = num3 = 10;
이 맞다고한다.
Console.ReadLine = scanf 라는걸 생각하자.
오... var을 쓰면 자동적으로 다 바뀌는구나 ㅋㅋ 개꿀 var만 쓰자~
그리고 논리연산자
연산자 설명
| && | 논리곱(AND) |
| || | 논리합(OR) |
| ! | 논리부정(NOT) |
이걸 정말 잘 이용해야된다는걸 안다. 제발 외우자
그리고 복합 대입 연산자.
연산자 예시 설명
| += | x += y; | x = x + y; |
| -= | x -= y; | x = x - y; |
| *= | x *= y; | x = x * y; |
| /= | x /= y; | x = x / y; |
| %= | x %= y; | x = x % y; |
이것도 잘 알아야한다.
1주차 사용자로부터 입력받기 과제
1. 이름과 나이
Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.WriteLine("이름과 나이를 적어주세요");
Console.Write("이름 : ");
string name = Console.ReadLine();
Console.Write("나이 : ");
string age1 = Console.ReadLine();
int age = int.Parse(age1);
Console.Write("이름은 "+ name +" 이고 ");
Console.Write("나이는 "+ age +" 살이구나");
2. 사칙연산
{
Console.WriteLine("사칙연산 계산 ( 숫자 기호 숫자 순으로 입력해주세요)");
Console.Write("계산 : ");
string input = Console.ReadLine();
string[] numbers = input.Split(' ');
int num1 = int.Parse(numbers[0]);
string sign = numbers[1];
int num2 = int.Parse(numbers[2]);
int result;
int remain;
if (sign == "+")
{
result = num1 + num2;
Console.WriteLine("몫 : " + result);
}
else if(sign == "-")
{
result = num1 - num2;
Console.WriteLine("몫 : " + result);
}
else if(sign == "*")
{
result = num1 * num2;
Console.WriteLine("몫 : " + result);
}
else if(sign == "/")
{
result = num1 / num2;
remain = num1 % num2;
Console.WriteLine("몫 : " + result);
Console.WriteLine("나머지 : " + remain);
}
else
{
Console.Write("올바르지않은 입력입니다");
return;
}
}
3.화씨 -> 섭씨
namespace FtoC
{
internal class Program
{
static void Main(string[] args)
{
float degree_f;
Console.Write("섭씨온도를 입력해주세요 : ");
string fitst_typing = Console.ReadLine();
float degree_c = int.Parse(fitst_typing);
degree_f = (degree_c - 32) * 5 / 9;
Console.WriteLine($"화씨온도 : {degree_f:F2}");
}
}
}
4.BMI 계산기
namespace Bmi
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("키와 몸무게를 적어주세요 : ");
Console.Write("키(cm) :");
string input1 = Console.ReadLine();
Console.Write("몸무게 :");
string input2 = Console.ReadLine();
float high = int.Parse(input1);
float weight = int.Parse(input2);
float bmi = weight / ((high / 100)*(high / 100));
Console.Write($"BMI수치 : {bmi:F2} ");
}
}
}
2주차 강의 에서는 잘 알고있는 if, else if,switch중첩 조건문은 그냥 듣기만으로 패스하고...
1주차에서 논리연산자 중요하다고했으니까... 그냥 외워두고...
코드의 지옥 for 문과 while 문으로 입문했다.
진짜 처음 했을때도 지옥같았지만, 더욱 지옥같은 부분이구나..
아 그리고 Do-while 문이라는것도있었지. 항상 while 에서 break 넣거나 for 안에 while 넣어서 잘 몰랐는데 이런것도있었지...
Foreach 문은 처음본다.
https://blockdmask.tistory.com/313 이곳에서 공부했는데
문법은 foreach(int 변수명 in 변수명) 인것같다.
그냥 while 문의 연장선? 이라고생각하면 될것같다.
음 그리고 enum 에서
enum Month {
January = 1, // 여기를 1로 시작한다고 명시
February,
March,
...
December
}
- anuary = 1이라고 명시했기 때문에,
- 그 다음 February는 자동으로 이전 값 + 1 = 2
- March는 3, April은 4 … 이런 식으로 자동 증가한다
이 부분이 처음알아서 재밋었다.
그리고 다차원 배열은... 쉬우니까... 패스...
다만 컬렉션? 에 대해서는 알아두자.
- List
- Dictionary
- Stack
- Queue
- HashSet
매서드랑 구조체는 다 아는거지만, 다시한번 복습하고
구조체는 많이 쓰이는거니까 꼭 다시공부해보자.
2주차 콘솔 맞추기 게임
1.숫자 맞추기 게임
using System;
using System.Security.Cryptography.X509Certificates;
namespace Number
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("숫자를 입력해주세요(0~100)");
int random;
Random rand = new Random();
random = rand.Next(100);
int number_change = 0;
while (random != number_change)
{
string input = Console.ReadLine();
number_change = int.Parse(input);
if (number_change < random)
{
Console.WriteLine("입력하신 숫자가 작습니다. 다시 입력해주세요");
}
else if (number_change > random)
{
Console.WriteLine("입력하신 숫자가 큽니다. 다시 입력해주세요");
}
else if (number_change == random)
{
Console.WriteLine("정답");
return;
}
else
{
Console.WriteLine("잘못된 입력값입니다.");
}
}
}
}
}
2.틱택토 게임
namespace tictacto
{
//https://velog.io/@wjstngus22/TIL-C-33-%ED%8B%B1%ED%83%9D%ED%86%A0-%EA%B2%8C%EC%9E%84-%EB%A7%8C%EB%93%A4%EA%B8%B0 참조
internal class Program
{
static int[,] Arrays()
{
//보드 만들기 위한 배열 생성
return new int[3, 3];
}
static void PrintBoard(int[,] board)
{
//보드 화면에 표시하기 위함
for (int ver = 0; ver < 3; ver++)
{
for (int hor = 0; hor < 3; hor++)
{
Console.Write(board[ver, hor] + " ");
}
Console.WriteLine();
}
}
static bool Check(int[,] board, int player)
{
// 나중에 승리 조건맞추기 위해서 가로,세로줄 체크하는법
// 가로 줄 체크
for (int i = 0; i < 3; i++)
{
if (board[i, 0] == player && board[i, 1] == player && board[i, 2] == player)
return true;
}
// 세로 줄 체크
for (int j = 0; j < 3; j++)
{
if (board[0, j] == player && board[1, j] == player && board[2, j] == player)
return true;
}
// 대각선 체크
if (board[0, 0] == player && board[1, 1] == player && board[2, 2] == player)
return true;
if (board[0, 2] == player && board[1, 1] == player && board[2, 0] == player)
return true;
return false;
}
static bool IsBoardFull(int[,] board)
{
//보드가 가득 찼을때 무승부로 만들기 위함
foreach (int cell in board)
{
if (cell == 0)
return false;
}
return true;
}
static void Main(string[] args)
{
int[,] board = Arrays();
int turn = 1;
while (true)
{
Console.Clear();
Console.WriteLine("현재 보드:");
PrintBoard(board);
Console.WriteLine($"\n플레이어 {turn} 차례입니다. 좌표를 입력하세요 (예: 1,2): ");
string[] input = Console.ReadLine().Split(',');
if (input.Length != 2 ||
!int.TryParse(input[0], out int x) ||
!int.TryParse(input[1], out int y) ||
x < 0 || x >= 3 || y < 0 || y >= 3)
{
Console.WriteLine("잘못된 입력입니다. 엔터를 눌러 다시 시도하세요.");
Console.ReadLine();
continue;
}
if (board[x, y] != 0)
{
Console.WriteLine("이미 선택된 자리입니다. 엔터를 눌러 다시 시도하세요.");
Console.ReadLine();
continue;
}
board[x, y] = turn;
// 승리 조건 체크
if (Check(board, turn))
{
Console.Clear();
PrintBoard(board);
Console.WriteLine($"\n플레이어 {turn} 승리.");
break;
}
// 무승부 체크
if (IsBoardFull(board))
{
Console.Clear();
PrintBoard(board);
Console.WriteLine("\n무승부입니다.");
break;
}
// 턴 넘기기
turn = (turn == 1) ? 2 : 1;
}
}
}
}
마무리
새로운 팀원들이랑 이야기하고, 코드 공유할수있어서 좋았다.
틱택토 게임 만들면서 내가 알고있지만 완벽하게 알지못하는구나... 라는 것도 다시금 느꼇다. 아직 배울게 많구나...
물론 완벽한건 없다지만 난 좀 많이 부족한것같다.
그럼에도 노력해야지. 피곤하지만... 피곤하지만...
오늘은 2병의 에너지 드링크를 마셨지만 내일은 몇병을 마실지가 궁금하다.