Assignment 1

연습문제 (1)


□ 단원 : C# 기초
□ 목표 : C# 프로그램 기초
□ 주요 연습 내용 : Visual Studio 2008, C# 입출력, 연산자, 변수, 제어문 사용 연습
□ 준비자료 : ScissorRockPaper.cs


1131903608.hwp1003723941.cs
연습문제 Ex1 (Due by 9/28 화 24시까지)
-cyber 강의실 (cyber.dku.edu)로 source code, executable file, solution/project VC# file, 보고서를 학번_이름_Ex1.zip으로 묶어서 낼 것. 보고서 (30%)


[연습문제]
1. 가위바위보 게임 프로그램 ScissorRockPaper 클래스를 작성하라. 이름(name)과 이긴 숫자(numWin)를 가진 게임 플레이어(Player) 구조체를 사용한다.  (30%)
– public enum Game { 가위=1, 바위=2, 보=3 };를 사용
– static Game GetRandomHand() 함수는 1,2,3 중 하나의 난수를 발생하여 enum type인 Game 값을 반환
  + 힌트: Random 클래스를 사용하여 1,2,3 중 하나의 난수를 발생시킴
– static Game GetHandByKeyboard() 함수는 키보드로 1(가위),2(바위),3(보)를 받아서 처리하여 enum type인 Game 값을 반환
  + 가위바위보 입력은 1,2,3 integer 값만을 입력받도록 해야 함
  + 힌트: while 문을 사용하여 1,2,3 integer가 아닌 경우 다시 입력을 받음
  + 힌트: Console.ReadLine() 함수는 string을 반환하므로, int로 변환하기 위하여  
      Parse 함수 사용 => intValue = int.Parse(string)
  + 힌트: TryParse 함수는 string을 integer로 변환이 가능하면, out 매개변수로 변환된
      값을 전달해 주고, true boolean 값을 반환  => boolValue = int.TryParse(string,
      out intValue)
– static void PrintWinner(Player player1, Player player2) 함수는 삼세판 가위바위보 게임하고 난 뒤 최종으로 승리한 사람이 누구인지 화면에 출력
  + 힌트: Player 구조체의 numWin이 더 큰 수를 가진 사람이 게임을 이긴다.


2. Main 함수에서는 2명의 게임 플레이어 객체를 생성하고 (1명은 컴퓨터이고, 다른 1명은 본인이 키보드로 입력함), 가위바위보 게임을 진행하는 routine을 추가한다. (20%)
– 힌트: GetHandByKeyboard와 GetRandomHand로 나온 바위>가위>보>바위를 판단함
– 힌트: do..while 문을 사용하여 만약 둘이 비긴 경우 계속 입력을 받도록 함
– 힌트: for 문을 사용하여 삼세판 가위바위보 게임을 진행함
– 힌트: 한 게임마다 이겼을 경우 Player 구조체의 numWin을 증가시킴


3. Main 함수에서 본인이 더 테스트해보고 싶은 ScissorRockPaper 클래스의 Method나 routine을 추가하라. (20%)

0부터 100까지 숫자만 입력받기


int value;  // needed for TryParse
string str; // needed for ReadLine


Console.Write(“0부터 100까지 숫자를 입력하세요: “);
str = Console.ReadLine();
while ((!int.TryParse(str, out value)) || (value < 0 || value > 100))
{
        Console.Write(“다시 0부터 100까지 숫자를 입력하세요: “);
        str = Console.ReadLine();
}
int result = int.Parse(str);
Console.WriteLine(“입력된 숫자=” + result);

Convert.ToInt32()와 Int32.Parse()와 Int32.TryParse() 비교

http://www.codeproject.com/KB/cs/AgileWare_Convert_Int32.aspx

Convert.ToInt32(string s)는 내부적으로 Int32.Parse(string s)을 불러서 string을 32-bit signed integer로 변환시켜주는 메소드

string s1 = 1234″;
string s2 = 1234.65″;
string s3 = null;
string s4 = 123456789123456789123456789123456789123456789″;

int result;
bool success;

result = Convert.ToInt32(s1); //— 1234
result = Convert.ToInt32(s2); //— FormatException
result = Convert.ToInt32(s3); //— 0
result = Convert.ToInt32(s4); //— OverflowException


Int32.Parse(string s)는 strng을 32-bit signed integer로 변환시켜주는 메소드
그러나 만약 s가 null일 경우 ArgumentNullException을 냄
또한 s가 integer가 아닐 경우 FormatException을 냄
또한 s가 integer의 MinValue또는 MaxVale를 넘칠 경우 OverflowException을 냄

result = Int32.Parse(s1); //— 1234
result = Int32.Parse(s2); //— FormatException
result = Int32.Parse(s3); //— ArgumentNullException
result = Int32.Parse(s4); //— OverflowException


Int32.TryParse(string s, out int i)는 string을 32-bit signed integer로 변환하여 out 에 보내주는 메소드로 성공하면 true를 반환
따라서 만약 s가 null일 경우 ArgumentNullException을 내지않고 false와 out으로 0을 반환
또한 s가 integer가 아닐 경우 FormatException을 내지않고 false와 out으로 0을 반환
또한 s가 integer의 MinValue또는 MaxVale를 넘칠 경우 OverflowException을 내지않고 false와 out으로 0을 반환


success = Int32.TryParse(s1, out result); //— success => true; result => 1234
success = Int32.TryParse(s2, out result); //— success => false; result => 0
success = Int32.TryParse(s3, out result); //— success => false; result => 0
success = Int32.TryParse(s4, out result); //— success => false; result => 0

const 상수와 readonly 상수의 비교

const 상수(constant)은 컴파일타임(compile-time) 상수이다.
readonly 상수(constant)은 런타임(run-time) 상수이다.

// const
public const int Millennium = 2000;
public const double PI = 3.141592;

// readonly
public static readonly int ThisYear = 2010;
public class MyClass
{
    public readonly double PI;
    public MyClass()
    {
        PI = 3.141592;
    }
}


const 상수는 선언하는 순간부터 static 된다.
const 상수를 선언함과 동시에 초기화를 해주어야 한다.
const 상수는 컴파일시 값이 결정 되어져 있어야 한다.

readonly 상수는 static 키워드를 사용하면 static 상수가 된다. 사용하지 않으면 일반상수가 된다.
readonly 상수는 const 키워드를 사용하는 것처럼 반드시 초기화 필요없.
readonly 상수는 생성자를 통해서 런타임시 값이 결정될 있다.
한번 값이 결정되면 다시는 값을 변경할 수는 없다.

Value Type과 Reference Type의 비교

값형식(Value Type)은 메모리를 직접 가리킨다.
참조형식(Reference Type)은 메모리를 참조를 통해서 가리킨다.

값형식(Value Type)은 변수의 선언과 동시에 메모리에 생성한다.
참조형식(Reference Type)은 변수의 선언과 메모리 생성 분리하여 생성한다.

값형식(Value Type)은 값형식끼리 할당 메모리의 값들을 그대로 복사한다.
참조형식(Reference Type)은 참조형식끼리 할당 할때 참조값만을 복사한다.

Stack과 Heap 비교

스택(Stack)은 Last-In, First-Out(LIFO) 방식으로 아이템을 저장하는 메모리의 자료 구조이다.
스택(Stack)은 지역변수(local variable)와 함수 리턴주소를 저장한다. C#에서 값형식(Value Type) 데이터는 스택에 저장된다.

힙(Heap)은 프로그램 코드 영역과는 별도로 유지되는 자유 메모리 공간이다.
힙(Heap)은 C#에서 new를 사용하여 메모리 할당하여 이 공간을 사용할 수 있다.
힙에 할당된 데이터는 전역변수(global variable)처럼 프로그램이 종료될 때까지 유지된다.
C#에서는 더이상 참조하지 않는 데이터를 자동으로 해제해준다 (gabage collection).
C#에서는 참조형식(Reference Type)은 스택에 메모리 주소를 저장하고 힙에 실질적인 데이터가 저장된다.

http://en.csharp-online.net/Stack_vs._Heap

Just another Kyoung Shin Park’s Lectures Sites site