Microsoft Word - hci11-midterm-answer.doc

Similar documents
Microsoft Word - java19-1-midterm-answer.doc

PowerPoint Presentation

JAVA PROGRAMMING 실습 08.다형성

Microsoft Word - java18-1-final-answer.doc

Microsoft Word - java19-1-final-answer.doc

PowerPoint Presentation

5장.key

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

금오공대 컴퓨터공학전공 강의자료

Microsoft PowerPoint - 2강

gnu-lee-oop-kor-lec06-3-chap7

Microsoft Word - cg07-midterm.doc

Design Issues

PowerPoint Template

Microsoft PowerPoint - CSharp-2-기초문법

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각

Microsoft PowerPoint - additional01.ppt [호환 모드]

PowerPoint 프레젠테이션

PowerPoint Presentation

Microsoft PowerPoint - Java7.pptx

Modern Javascript

쉽게 풀어쓴 C 프로그래밍

PowerPoint Presentation

PowerPoint 프레젠테이션

C# Programming Guide - Types

단국대학교멀티미디어공학그래픽스프로그래밍중간고사 (2011 년봄학기 ) 2011 년 4 월 26 일학과학번이름 중간고사 담당교수 : 단국대학교멀티미디어공학전공박경신 l 답은반드시답안지에기술할것. 공간이부족할경우반드시답안지몇쪽의뒤에있다고명기한후기술할것. 그외의경우의답안지뒤

PowerPoint Presentation

자바 프로그래밍

PowerPoint Presentation

초보자를 위한 C# 21일 완성

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍

Microsoft PowerPoint - hci2-lecture6 [호환 모드]

PowerPoint Presentation

class Sale void makelineitem(productspecification* spec, int qty) SalesLineItem* sl = new SalesLineItem(spec, qty); ; 2. 아래의액티비티다이어그램을보고 Java 또는 C ++,

(Microsoft Word - \301\337\260\243\260\355\273\347.docx)

PowerPoint Presentation

PowerPoint 프레젠테이션

중간고사

PowerPoint Presentation

선형대수학 Linear Algebra

JAVA PROGRAMMING 실습 05. 객체의 활용

PowerPoint 프레젠테이션

Microsoft PowerPoint - additional08.ppt [호환 모드]

05-class.key

chap10.PDF

Microsoft PowerPoint - CSharp-10-예외처리

JAVA PROGRAMMING 실습 02. 표준 입출력

1. 객체의생성과대입 int 형변수 : 선언과동시에초기화하는방법 (C++) int a = 3; int a(3); // 기본타입역시클래스와같이처리가능 객체의생성 ( 복습 ) class CPoint private : int x, y; public : CPoint(int a

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

Microsoft PowerPoint - C++ 5 .pptx

(8) getpi() 함수는정적함수이므로 main() 에서호출할수있다. (9) class Circle private double radius; static final double PI= ; // PI 이름으로 로초기화된정적상수 public

슬라이드 1

C++ Programming

슬라이드 1

PowerPoint Presentation

PowerPoint Presentation

Cluster management software

PowerPoint Presentation

교육자료

K&R2 Reference Manual 번역본

쉽게 풀어쓴 C 프로그래밍

ThisJava ..

No Slide Title

Microsoft PowerPoint - Lect04.pptx

PowerPoint 프레젠테이션

C++ Programming

17장 클래스와 메소드

Microsoft PowerPoint - Chapter 6.ppt

PowerPoint Presentation

JAVA PROGRAMMING 실습 05. 객체의 활용

4장.문장

C++ Programming

Chapter 6 Objects and Classes

유니티 변수-함수.key

JAVA PROGRAMMING 실습 07. 상속

0. 표지에이름과학번을적으시오. (6) 1. 변수 x, y 가 integer type 이라가정하고다음빈칸에 x 와 y 의계산결과값을적으시오. (5) x = (3 + 7) * 6; x = 60 x = (12 + 6) / 2 * 3; x = 27 x = 3 * (8 / 4

Microsoft PowerPoint - 07-C#-2-기초문법.ppt [호환 모드]

제11장 프로세스와 쓰레드

PowerPoint 프레젠테이션

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt

TEST BANK & SOLUTION

JUNIT 실습및발표

A Tour of Java IV

02 C h a p t e r Java

01-OOPConcepts(2).PDF

슬라이드 1

A Tour of Java V

비긴쿡-자바 00앞부속

JAVA PROGRAMMING 실습 09. 예외처리

Microsoft PowerPoint - lec2.ppt

09-interface.key

설계란 무엇인가?

Spring Boot/JDBC JdbcTemplate/CRUD 예제

Microsoft PowerPoint 세션.ppt

C++ Programming

Microsoft PowerPoint - additional06.ppt [호환 모드]

Transcription:

중간고사 담당교수 : 단국대학교멀티미디어공학전공박경신 답은반드시답안지에기술할것. 공간이부족할경우반드시답안지몇쪽의뒤에있다고명기한후기술할것. 그외의경우의답안지뒤쪽이나연습지에기술한내용은답안으로인정안함. 답에는반드시네모를쳐서확실히표시할것. 답안지에학과, 학번, 이름외에본인의암호를기입하면성적공고시학번대신암호를사용할것임. 1. 다음프로그램의실행결과를써라. 전역변수와지역변수에주의할것. (10 점 ) class MethodTest static int i = 5; static void Multiply1(int i) i *= 2; Console.WriteLine("Multiply1 : i=" + i.tostring()); static int Multiply2(int a, int b) int i = 2; i *= 2; Console.WriteLine("Multiply2 : i=" + i.tostring()); Multiply1(i); int c = a * b; Console.WriteLine("Multiply2 : a=0 b=1 c=2", a, b, c); return c; static void Multiply3(int a, int b, ref int c) i *= 2; Console.WriteLine("Multiply3 : i=" + i.tostring()); c = Multiply2(a, b); Console.WriteLine("Multiply3 : c=" + c.tostring()); static void Main() Console.WriteLine("Main1: i=" + i.tostring()); i *= 2; Console.WriteLine("Main2: i=" + i.tostring()); Multiply1(i); 1/13

Console.WriteLine("Main3: i=" + i.tostring()); int a = 3, b = 4, c = 6; Multiply3(a, b, ref c); Console.WriteLine("Main4: i=" + i.tostring()); 출력결과 : Main1 : i=5 Main2 : i=10 Multiply1 : i=20 Main3 : i=10 Multiply3 : i=20 Multiply2 : i=4 Multiply1 : i=8 Multiply2 : a=3 b=4 c=12 Multiply3 : c=12 Main4 : i=20 2. StandardWeightCalculator 프로그램의다음메소드들의내부구현을하라. (10 점 ) enum Gender Female, Male enum BMI Underweight, Normal, Overweight, Obesity enum Activity Low, Medium, High // GetGenderFromString 메소드는 str값을남녀에따라 Gender 열거형으로반환 Gender GetGenderFromString(string str) if (str == " 남 " str == "M") return Gender.Male; return Gender.Female; // GetNormalWeight 메소드는남녀별로신장 (cm) 을이용하여표준체중 (kg) 를계산 // 남자표준체중 = 신장 (cm) x 신장 (cm) x 22 x 0.0001f // 여자표준체중 = 신장 (cm) x 신장 (cm) x 21 x 0.0001f float GetNormalWeight(float height, Gender gender) if (gender == Gender.Male) return height * height * 22; return height * height * 21; 2/13

// GetBMI 메소드는기준에근거하여 BMI 열거형으로반환 // BMI = 체중 (kg)/ 신장^2(m^2) // BMI계산값이 20미만저체중, 20~24 정상, 25~29 과체중, 30이상비만 BMI GetBMI(float height, float weight) float bmi = weight / (height * 0.01f)/ (height * 0.01f); Console.WriteLine("bmi=" + bmi); if (bmi < 20.0) return BMI.Underweight; if (bmi >= 20.0 && bmi < 24.0) return BMI.Normal; if (bmi >= 24.0 && bmi < 30.0) return BMI.Overweight; return BMI.Obesity; // GetActivityFromString 메소드는 str값이 Low/Medium/High에따라 Activity 열거형으로반환 Activity GetActivityFromString(string str) if (str == "Low") return Activity.Low; if (str == "Medium") return Activity.Medium; return Activity.High; 3/13

3. 값형식과참조형식에대한 Pass-by-value 와 Pass-by-reference 메소드매개변수전달방식을본인이직접예를들어간단히설명하라. (10 점 ) Pass value type by value ( 값형식을값에의한전달방식 ) - 값형식 (value type) 은값을 copy 하여매개변수에전달 - static void Square1(int x) x*= x; Console.WriteLine( The value inside: 0, x); // 함수내부에선변경된값이출력 static void Main() int i =5; Square1(i); Console.WriteLine( i=0, i); // 그러나, 함수에서변경된값이외부에반영되지않음 Pass reference type by value ( 참조형식을값에의한전달방식 ) - 참조형식 (reference type) 은참조를 copy 하여매개변수에전달 - static void ChangeArray1(int[] arr) arr[0] = 888; // 메인의 myarray 를같이참조하고있으므로 myarray[0]=888 로변경 arr = new int[5] -3, -1, -2, -3, -4; // 함수내부에서 arr 는새로지정 Console.WriteLine( The value inside: arr[0]=0, arr[0]); // 새로지정된배열로출력 static void Main() int[] myarray =1, 4, 5; ChangeArray1(myArray); Console.WriteLine( myarray[0]=0, myarray[0]); // myarry[0]=888 로출력 Pass value type by reference ( 값형식을참조에의한전달방식 ) - ref 키워드를사용하여, 값형식 (value type) 을참조에의한전달방식을사용 - static void Square2(ref int x) x*= x; Console.WriteLine( The value inside: 0, x); // 메인 i 를참조하므로값이변경 static void Main() int i =5; Square2(i); Console.WriteLine( i=0, i); // 함수에서변경된값이외부로반영됨 Pass reference type by reference ( 참조형식을참조에의한전달방식 ) - ref 키워드를사용하여, 참조형식 (reference type) 을참조에의한전달방식을사용 - static void ChangeArray2(ref int[] arr) arr[0] = 888; // 메인의 myarray 를같이참조하고있으므로 myarray[0]=888 로변경 arr = new int[5] -3, -1, -2, -3, -4; // 그러나원본배열이다시변경 Console.WriteLine( The value inside: arr[0]=0, arr[0]); // 새로지정된배열로출력 static void Main() int[] myarray =1, 4, 5; ChangeArray2(myArray); Console.WriteLine( myarray[0]=0, myarray[0]); // myarry[0]=-3 로출력 4/13

4. 다음 A 클래스에서포함하는 Size 클래스를정의하라. Size 클래스는 Width 와 Height 속성과생성자와 Print 그리고 ToString 메소드를갖는다. (10 점 ) enum Color Red, Green, Blue abstract class A public Color FillColor public Point Position public Size Size public A(Color fillcolor, Point position, Size size) this.fillcolor = fillcolor; this.position = position; this.size = size; public abstract void Draw(); class Point public int X public int Y public Point() : this(0, 0) public Point(int x, int y) this.x = x; this.y = y; public void SetPosition(int x, int y) this.x = x; this.y = y; public virtual void Print() Console.WriteLine("Point (0,1)", X, Y); public override string ToString() return (String.Format("(0,1)", X, Y)); class Size public int Width public int Height public Size() : this(0, 0) public Size(int width, int height) this.width = width; this.height = height; public virtual void Print() Console.WriteLine("Size (0x1)", Width, Height); public override string ToString() return (String.Format("(0,1)", Width, Height)); 5/13

5. 다음 Point3D 클래스와 Point4D 클래스의메소드를모두구현하라. base 와 this 키워드를사용하여코드를간결하게작성한다. (10 점 ) class Point3D : Point public int Z public Point3D() : this(0, 0, 0) public Point3D(int x, int y, int z) : base(x, y) this.z = z; public void SetPosition(int x, int y, int z) base.setposition(x, y); this.z = z; public override void Print() Console.WriteLine("Point3D (0,1,2)", X, Y, Z); public override string ToString() return (String.Format("Point3D (0, 1, 2)", X, Y, Z)); class Point4D : Point3D public int W public Point4D() : this(0, 0, 0, 0) public Point4D(int x, int y, int z, int w) : base(x, y, z) this.w = w; public void SetPosition(int x, int y, int z, int w) base.setposition(x, y, z); this.w = w; public override void Print() Console.WriteLine("Point4D (0,1,2,3)", X, Y, Z, W); public override string ToString() return (String.Format("Point4D (0, 1, 2,3)", X, Y, Z, W)); 6/13

6. 다음은 B, C, D, E 클래스를추가적으로보여주고있다. 다형성 (Polymorphism) 이무엇인지예를들어자세히설명하라. 그리고 Main 메소드의출력결과를적어라. (10 점 ) class B : A public B(Color fillcolor, Point position, Size size) : base(fillcolor, position, size) public override void Draw() Console.WriteLine("B 는 (0 1) 에 2x3 크기와 4 색 ", Position.X, Position.Y, Size.Width, Size.Height, FillColor); class C : A public C(Color fillcolor, Point position, Size size) : base(fillcolor, position, size) public override void Draw() Console.WriteLine("C 는 (0 1) 에 2x3 크기와 4 색 ", Position.X, Position.Y, Size.Width, Size.Height, FillColor); class D : A public D(Color fillcolor, Point position, Size size) : base(fillcolor, position, size) public override void Draw() Console.WriteLine("D 는 (0 1) 에 2x3 크기와 4 색 ", Position.X, Position.Y, Size.Width, Size.Height, FillColor); class E : D public E(Color fillcolor, Point position, Size size) : base(fillcolor, position, size) if (size.width < size.height) Size.Height = size.width; Size.Width = size.height; public sealed override void Draw() Console.WriteLine("E 는 (0 1) 에 2x3 크기와 4 색 ", Position.X, Position.Y, Size.Width, Size.Height, FillColor); class Program static void Main(string[] args) A[] alist = new A[5] new C(Color.Red, new Point(0, 0), new Size(10, 30)), new D(Color.Green, new Point(20, 30), new Size(10, 30)), new B(Color.Blue, new Point(30, 40), new Size(20, 30)), new E(Color.Blue, new Point(50, 60), new Size(40, 50)), new D(Color.Blue, new Point(10, 20), new Size(20, 30)) 7/13

; foreach (var elem in alist) elem.draw(); Point p1 = new Point(1, 2); Point3D p2 = new Point3D(10, 11, 12); Point4D p3 = new Point4D(20, 21, 22, 23); Console.WriteLine("p1: 0", p1); Console.WriteLine("p2: 0", p2); Console.WriteLine("p3: 0", p3); p1 = p2; p2 = p3; p1.print(); p2.print(); p3.print(); p2.setposition(4, 5, 6); Console.WriteLine("p2: 0", p2); p3 = (Point4D)p2; Console.WriteLine("p3: 0", p3); Point4D p4 = (Point4D)p3; Console.WriteLine("p4: 0", p4); 다형성 상속을통해클래스를한개이상의형식으로사용할수있는것을다형성이라고 한다. 상위클래스에서선언된메소드를하위클래스에서재정의 (override) 하고실행시간에새로 정의된 override 된멤버의내용으로처리 (late binding) 한다. 예를들어 - p1 = p2; // upcasting; p1 은 Point3D 객체 (10,11,12) p2 = p3; // upcasting; p2 는 Point4D 객체 (20,21,22,23) p2.setposition(4, 5, 6); // p2 가실제 Point4D 객체 (20,21,22,23) 이므로 (4,5,6,23) 로변경 p3 = (Point4D)p2; // downcasting; p2 가실제로 Point4D 객체이므로 p3 도 Point4D 객체 Point4D p4 = (Point4D)p3; // downcasting; p3 가실제로 Point4D 객체이므로 p4 도 Point4D 객체 실행결과 C 는 (0 0) 에 10x30 크기와 Red 색 D 는 (20 30) 에 10x30 크기와 Green 색 B 는 (30 40) 에 20x30 크기와 Blue 색 E 는 (50 60) 에 40x40 크기와 Blue 색 D 는 (10 20) 에 20x30 크기와 Blue 색 p1: (1, 2) p2: (10, 11, 12) p3: (20, 21, 22, 23) Point3D (10, 11, 12) Point4D (20, 21, 22, 23) Point4D (20, 21, 22, 23) p2: (4, 5, 6, 23) p3: (4, 5, 6, 23) p4: (4, 5, 6, 23) 8/13

7. 위의 4-6 번예제에서밑줄친 virtual/override 와 abstract/override 그리고 sealed 의차이점이무엇인지예를들어간단히서술하라. (10 점 ) virtual/override : Point, Size 클래스의 public virtual void Print().. 는이클래스를상속받는파생클래스에서이메소드를재정의할수있다는의미로 virtual 로지정한다. Point 를상속받은 Point3D, 그리고 Point3D 를상속받은 Point4D 의 public override void Print().. 에서추가된부분에대한구현을재정의한다. Point, Size, Point3D, Point4D 클래스의 public override void ToString() 는모든클래스가 System.Object 에서상속받아서각클래스에맞게 ToString() 을재정의해서사용한다. abstract/override : 추상클래스 A 에 public abstract void Draw(); 는 abstract 으로지정된메소드로내부구현을할수없다. A 를상속받은 B, C, D, E 클래스의 public override void Draw().. 에서내부구현을해야한다. sealed : E 클래스의 public sealed override void Draw().. 에서는 sealed 하여 E 클래스를상속하여사용하는클래스에서이메소드를더이상재정의해서사용할수없음을지정한다. 8. 위의 Point 클래스를참조하여값형식과참조형식을비교한다. 이프로그램이실행되는출력결과를써라. (10 점 ) static void Main() int val1 = 5; int val2 = 10; if (val1 == val2) Console.WriteLine("val1 == val2"); Console.WriteLine("val1!= val2"); object val3 = val1; object val4 = val1; if (val3 == val4) Console.WriteLine("val3 == val4"); Console.WriteLine("val3!= val4"); int val5 = (int)val3; int val6 = (int)val4; if (val5 == val6) Console.WriteLine("val5 == val6"); Console.WriteLine("val5!= val6"); Point pos1 = new Point(val1, val2); Point pos2 = new Point(val1, val2); if (pos1 == pos2) Console.WriteLine("pos1 == pos2"); Console.WriteLine("pos1!= pos2"); 9/13

if (pos1.x == pos2.x) Console.WriteLine("pos1.X == pos2.x"); Console.WriteLine("pos1.X!= pos2.x"); if (pos1.y == pos2.y) Console.WriteLine("pos1.Y == pos2.y"); Console.WriteLine("pos1.Y!= pos2.y"); Point pos3 = pos1; Point pos4 = pos1; if (pos3 == pos4) Console.WriteLine("pos3 == pos4"); Console.WriteLine("pos3!= pos4"); object pos5 = pos3; object pos6 = pos4; if (pos5 == pos6) Console.WriteLine("pos5 == pos6"); Console.WriteLine("pos5!= pos6"); Point pos7 = (Point) pos6; if (pos1 == pos7) Console.WriteLine("pos1 == pos7"); Console.WriteLine("pos1!= pos7"); if (pos2 == pos7) Console.WriteLine("pos2 == pos7"); Console.WriteLine("pos2!= pos7"); Console.WriteLine(); 출력결과 : val1!= val2 val3!= val4 val5 == val6 pos1!= pos2 pos1.x == pos2.x pos1.y == pos2.y pos3 == pos4 pos5 == pos6 pos1 == pos7 pos2!= pos7 10/13

9. IEquatable 와 IComparable 인터페이스를간단히설명하라. 다음 Point 클래스에 IEquatable<T> 와 IComparable<T> 인터페이스를상속받아구현 (implement) 하라. (10 점 ) interface IEquatable<T> bool Equals(T obj); interface IComparable<T> int CompareTo(T obj); class Point : IEquatable<Point>, IComparable<Point> // 중간생략 // Point 클래스의 X 와 Y 가모두같으면 true 아니면 false public bool Equals(Point other) if (this.x == other.x && this.y == other.y) return true; return false; // Point 클래스의 X 가같으면 Y 가누가더큰지를비교 public int CompareTo(Point other) if (this.x == other.x) return this.y.tocompare(other.y); return this.x.tocompare(other.x); IEquatable 인터페이스 : IEquatable 인터페이스는현객체가동일한형태의다른객체와같은지여부를확인하는 Equals 메소드를제공하는인터페이스로, 현객체가 obj 인수의값과같으면 true, 다르면 false를반환하도록구현한다. == 와!= 연산자오버로딩이함께되어있을때두객체의내용이같은지비교하는데사용된다. IComparable 인터페이스 : IComparable 인터페이스는현객체를동일한형식의다른객체와비교하는 ( 인터페이스정렬순서를확인하는 ) CompareTo 메소드를제공하는인터페이스로, 현객체가 obj 인수보다작으면 0보다작은수를같으면 0을그면 0보다큰수를반환하도록구현한다. 컬렉션을사용할시 Sort ( 정렬 ) 할때사용된다. 11/13

10. 다음 Main 메소드에밑줄친네줄의코드를 TestA, TestB, Print, PrintThree 메소드를사용하여수정하라. (5 점 ) class NumValue public int A public static int B public const int THREE=3; public NumValue(int a, int b) A = a; B = b; public bool TestA(int value) return A > value; public static bool TestB(int value) return B == value; public void Print() Console.WriteLine("a=0 b=1", A, B); public static void PrintThree() Console.WriteLine("Three!"); class NumValueTest static void Main() NumValue n = new NumValue(5, 3); if (n.a > NumValue.THREE) Console.WriteLine("a=0 b=1", n.a, NumValue.B); if (NumValue.B == NumValue.THREE) Console.WriteLine("Three!"); if (n.testa(numvalue.three)) n.print(); if (NumValue.TestB(NumValue.THREE)) NumValue.PrintThree(); 12/13

11. 다음은원하는온도변환방법을지정하여사용할수있는프로그램이다. 빈칸을채워라. (5 점 ) public delegate double Conversion(double from); class DelegateTest static double F2C( double f ) return (f - 32.0) * (5.0 / 9.0); static double C2F( double c ) return ((9.0 / 5.0) * c + 32.0); // factory method for returning delegate static public Conversion GetConversionMethod(string conversiontype) Conversion conversion; switch (conversiontype) case "C2F": conversion = new Conversion(C2F); break; case "F2C": conversion = new Conversion(F2C); break; default: throw new ArgumentException(" 알수없는 conversion type: "+conversiontype); return conversion; // user input to temperature and type of conversion static public void GetUserInput(out double temperature, out string conversiontype) Console.WriteLine("Temperature Converter"); Console.WriteLine("C2F: Celsius => Fahrenheit"); Console.WriteLine("F2C: Fahrenheit => Celsius"); Console.Write(" 원하는온도변환을입력하시오 (C2F or F2C): "); conversiontype = Console.ReadLine(); Console.Write(" 변환하고자하는온도를입력하시오 : "); temperature = Double.Parse(Console.ReadLine()); static public void Main() double temperature; string conversiontype; GetUserInput(out temperature, out conversiontype); Conversion doconversion = GetConversionMethod(conversionType); double result = doconversion(temperature); Console.WriteLine("\n conversiontype=0 Temperature=1 Result=2\n", conversiontype, temperature, result); - 끝 - 13/13