본문 바로가기
공부/C#

C# 공부(7) 61~70

by 라이티아 2024. 8. 26.

61. Random 클래스

using System;

namespace P61
{
    class Program
    {
        static void Main(string[] args)
        {
            Random r = new Random();
            Console.WriteLine("{0, -16}", "Random Bytes");
            Byte[] b = new byte[5];
            r.NextBytes(b);

            foreach(var x in b) Console.Write($"{x, 12}");
            Console.WriteLine();

            Console.Write("{0, -16}", "Random Double");
            double[] d = new double[5];
            
            for (int i = 0; i < 5; i++) d[i] = r.NextDouble();

            foreach (var x in d) Console.Write("{0, 12:F8}", x);
            Console.WriteLine();


            Console.Write("{0, -16}", "Random Int");
            int[] a = new int[5];
            for (int i = 0; i < 5; i++) a[i] = r.Next();
            Print(a);


            Console.Write("{0, -16}", "Random 0 - 99");
            int[] v = new int[5];
            for(int i = 0; i<5; i++) v[i] = r.Next(100);
            Print(v);
        }

        private static void Print(int[] value)
        {
            foreach(var x in value) Console.Write(x + " ");
            Console.WriteLine();
        }
    }
}

 

결과

Random Bytes
         141         217          21          24         245
Random Double     0.11305688  0.17245586  0.03691998  0.88368851  0.18220766
Random Int      2139771956 463178747 454599262 954349239 510822117
Random 0 - 99   89 14 62 12 35

 

Random의 사용에 대한 코드이다. 설마 Random이라는 클래스가 따로 있는지는 몰랐다. 보통 Random.range로 사용해서 잘 몰랐는데, 신기하다

 

62. 배열에서 최소, 최대, 평균 계산

using System;

namespace P62
{
    class Program
    {
        static void Main(string[] args)
        {
            Random r = new Random();
            int[] v = new int[20];

            for (int i = 0; i < v.Length; i++)
            {
                v[i] = r.Next(100);
            }
            PrintArray(v);

            int max = v[0];
            for (int i = 0; v.Length > i; i++) if (v[i] > max) max = v[i];
            Console.WriteLine("최대값 : " + max);

            int min  = v[0];
            for (int i = 0; v.Length > i; i++) if (v[i] < min) min = v[i];
            Console.WriteLine("최소값 : " +  min);

            int sum = 0;
            for (int i =0; v.Length > i;i++) sum += v[i];
            Console.WriteLine($"합계 {sum}, 평균 {sum / v.Length}");
        }
        private static void PrintArray<T>(T[] value)
        {
            for (int i = 0; value.Length > i; i++)
            {
                Console.Write($"{value[i],5} ");
            }
            Console.WriteLine();
        }
    }
}

 

결과

   37    65    42    69    94    65    68    67    94    17    19    23    12     3    34    26    67    78     0    64
최대값 : 94
최소값 : 0
합계 944, 평균 47

 

배열의 요소를 반복문을 통해 검사하는 과정을 나타낸 코드이다

 

63. 선형탐색과 이진탐색

using System;

namespace P63
{
    class Program
    {
        static void Main(string[] args)
        {
            Random r = new Random();
            int[] v = new int[30];

            for (int i = 0; i < 30; i++) v[i] = r.Next(1000); 
            PrintArray(v);

            Array.Sort(v); // 정렬
            PrintArray(v);

            Console.Write("검색할 숫자 입력 : ");
            int input = int.Parse(Console.ReadLine());

            int count = 0;

            for (int i = 0; i < v.Length; i++) // 선형 탐색
            {
                count++;
                if (v[i] == input) { Console.WriteLine($"값 발견, 위치 v[{i}], 비교 횟수 {count}"); break; }
            }

            count = 0;
            int low = 0;
            int high = v.Length - 1;
            while (low <= high)
            {
                count++;
                int mid = (low + high) / 2;
                if (input == v[mid])
                {
                    Console.WriteLine($"v[{mid}] = {v[mid]} 탐색 횟수 {count}");
                    break;
                }
                else if (input > v[mid]) low = mid + 1;
                else high = mid - 1;
            }
        }
        private static void PrintArray<T>(T[] value)
        {
            foreach (T item in value) Console.Write(item + " ");
            Console.WriteLine();
        }
    }
}

 

결과

585 723 15 433 162 504 725 450 439 413 313 661 850 106 798 696 616 473 474 249 870 808 81 91 652 120 523 997 878 961
15 81 91 106 120 162 249 313 413 433 439 450 473 474 504 523 585 616 652 661 696 723 725 798 808 850 870 878 961 997
검색할 숫자 입력 : 433
값 발견, 위치 v[9], 비교 횟수 10
v[9] = 433 탐색 횟수 5

 

반복문을 이용해서 정렬된 배열에서 선형 탐색, 이진 탐색을 해보는 코드이다.

 

64. 버블 정렬

using System;

namespace P64
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] v = { 3, 5, 2, 7, 1 };
            PrintArray(v);

            for (int i = 4; i > 0; i--)
            {
                for(int j = 0; j < i; j++)
                {
                    if (v[j] > v[j + 1])
                    {
                        int sub = v[j];
                        v[j] = v[j + 1];
                        v[j + 1] = sub;
                    }
                }
            }
            PrintArray(v);
        }
        private static void PrintArray<T>(T[] value)
        {
            foreach (T item in value) Console.Write(item + " ");
            Console.WriteLine();
        }
    }
}

 

결과

3 5 2 7 1
1 2 3 5 7

 

정렬 방법중 버블 정렬에 관한 코드이다. 근데 언제 써야할지 모르겠다. 시간 복잡도에서 우위에 있다...?

아마 코딩 테스트떄 쓸일이 있지 않을까 싶다

 

65. 클래스와 구조체

using System;

namespace P65
{
    struct DateStruct
    {
        public int year, month, day;
    }

    class DateClass
    {
        public int year, month, day;
    }
    class Program
    {
        static void Main(string[] args)
        {
            //int computer_price = 71968 + 23005 + 42001 + 2662 + 86497 + 51908;
            //Console.WriteLine(computer_price);

            DateStruct sDay;
            sDay.year = 2018;
            sDay.month = 11;
            sDay.day = 22;
            Console.WriteLine($"{sDay.year} {sDay.month} {sDay.day}");

            DateClass cDay = new DateClass();
            cDay.year = 2018;
            cDay.month = 11;
            cDay.day = 22;
            Console.WriteLine($"{cDay.year} {cDay.month} {cDay.day}");

            DateStruct sDay2 = new DateStruct();
            Console.WriteLine($"{sDay2.year} {sDay2.month} {sDay2.day}");

            DateClass cDay2 = new DateClass();
            Console.WriteLine($"{cDay2.year} {cDay2.month} {cDay2.day}");

            DateStruct s = sDay;
            DateClass c = cDay;

            s.year = 2000;
            c.year = 2000;

            Console.WriteLine($"s {s.year} {s.month} {s.day}");
            Console.WriteLine($"c {c.year} {c.month} {c.day}");
            Console.WriteLine($"{sDay.year} {sDay.month} {sDay.day}");
            Console.WriteLine($"{cDay.year} {cDay.month} {cDay.day}");
        }
    }
}

 

결과

2018 11 22
2018 11 22
0 0 0
0 0 0
s 2000 11 22
c 2000 11 22
2018 11 22
2000 11 22

 

(첫 2줄은 새로사는 컴퓨터 가격 계산이다 무시)

객체지향의 꽃 class이다 눈여겨 봐야 할 곳은 기본 값이 0인 것과, 복사, 값 변경시 class는 ref같은 개념이기에 heap영역값이 변화하여 출력에 변화가 생긴다

 

66. 클래스의 멤버, 필드와 상수

using System;

namespace P66
{
    class Product
    {
        public string name;
        public int price;
    }
    class MyMath
    {
        public static double PI = 3.14;
    }
    class MyCalendar
    {
        public const int months = 12;
        public const int weeks = 52;
        public const int days = 365;

        public const double daysPerWeek = (double)days / (double)weeks;
        public const double daysPerMonth = (double)days / (double)months;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Product p = new Product();
            p.name = "Test";
            p.price = 100;

            Console.WriteLine($"{p.name} {p.price}");
            Console.WriteLine($"원주율 : {MyMath.PI}");
            Console.WriteLine($"한달은 평균 {MyCalendar.daysPerMonth :F3}");
        }
    }
}

 

결과

Test 100
원주율 : 3.14
한달은 평균 30.417

 

const를 사용하는 코드이다. const로 선언된 변수는 컴파일 중에는 값을 변경할 수 없다.

 

67. 인스턴스 메소드와 스태틱 메소드

using System;
namespace P67
{
    class Date
    {
        public int year, month, day;

        public static bool IsLeapYear(int year)
        {
            return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
        }
        static int[] days = { 0, 31, 69, 90, 120, 151, 181, 212, 243, 273, 304, 334 };

        public int DayOfYear()
        {
            return days[month - 1] + day + (month > 2 && IsLeapYear(year) ? 1 : 0);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Date xmas = new Date();

            xmas.year = 2018;
            xmas.month = 12;
            xmas.day = 25;

            Console.WriteLine($"{xmas.year} {xmas.month} {xmas.day}는 {xmas.DayOfYear()}일째 되는 날");

            if (Date.IsLeapYear(2018)) Console.WriteLine("2018 윤년");
            else Console.WriteLine("2018 윤년x");
        }
    }
}

 

결과

2018 12 25는 359일째 되는 날
2018 윤년x

 

static을 붙인 메소드는 클래스명.메소드()로 사용할 수 있다.

static이 없을시 인스턴스 메소드라고 정의된다.

 

68. 생성자 메소드

using System;

namespace P68 // 생성자
{
    class Date
    {
        private int _year, _month, _day;

        public Date()
        {
            _year = 1;
            _month = 1;
            _day = 1;
        }

        public Date(int y, int m ,int d)
        {
            _year = y;
            _month = m;
            _day = d;
        }

        public void Print()
        {
            Console.WriteLine($"{_year} {_month} {_day}");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Date test = new Date(2000, 11, 22);
            Date test2 = new Date();

            test.Print();
            test2.Print();
        }
    }
}

 

결과

2000 11 22
1 1 1

 

cpp에서 사용하던것과 같은 생성자 개념을 알려주는 코드이다.

본 코드에서는 디폴트 생성자와 일반 생성자에 대해서 정의했다

 

69. 속성

using System;

namespace P69 // 속성
{
    class Rectangle
    {
        private double width;
        private double height;

        public double GetWidth() { return width; }
        public double GetHeight() { return height; }

        public void SetWidth(double w) { if (w > 0) width = w; }
        public void SetHeight(double h) { if (h > 0) height = h; }
    }

    class RectWithProp
    {
        public double Width { get; set; }
        public double Height { get; set; }
    }

    class RectWithPropFull
    {
        private double width;
        public double Width { get { return width; } set { if (value > 0) width = value; } }

        private double height;
        public double Height { get { return height; } set { if (value > 0) height = value; } }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            r.SetWidth(10.0);
            r.SetHeight(10.0);
            Console.WriteLine($"r의 면적 {r.GetWidth() * r.GetHeight()}");

            RectWithProp r1 = new RectWithProp();
            r1.Width = 10.0;
            r1.Height = 10.0;
            Console.WriteLine($"r1의 면적 {r1.Width * r1.Height}");

            RectWithPropFull r2 = new RectWithPropFull();
            r2.Width = 10.0;
            r2.Height = 10.0;
            Console.WriteLine($"r2의 면적 {r2.Width * r2.Height}");

            RectWithPropFull r3 = new RectWithPropFull();
            r3.Width = 10.0;
            r3.Height = -10.0;
            Console.WriteLine($"r2의 면적 {r3.Width * r3.Height}");
        }
    }
}

 

결과

r의 면적 100
r1의 면적 100
r2의 면적 100
r2의 면적 0

 

C#의 get, set를 활용하는 코드이다. 솔직히 정확하게 모르는 부분이 많은 것 같다.

1번이 흔히 처음 배우는 setet geter를 사용하는 방법이고, 2번부터가 속성을 사용하는 예시이다.

속성에 추가적으로 코드를 넣어 원하는 형태로 수정할 수 있는 것도 눈여겨볼만한 요소인 것 같다.

 

70. 세 개의 숫자 중 가장 큰 수를 찾는 정적 메소드

using System;

namespace P70
{
    class Program
    {
        /*
        static void Main(string[] args)
        {
            int a = 10, b = 30, c = 20;
            Program x = new Program();
            Console.WriteLine($"가장 큰 수는 {x.Larger(x.Larger(a, b), c)}");
        }
        private int Larger(int a, int b)
        {
            return (a >  b) ? a : b;
        }
        */
        static void Main(string[] args)
        {
            int a = 10, b = 30, c = 20;
            Console.WriteLine($"가장 큰 수는 {Larger(Larger(a, b), c)}");
        }
        private static int Larger(int a, int b)
        {
            return (a > b) ? a : b;
        }
    }
}

 

결과

가장 큰 수는 30

 

static을 사용하면 어떻게 코드가 편하게 변하는지를 보여주는 코드이다.

static이 없을시 굳이 필요없는 객체를 만들 필요가 없어진다.

 

 

C-sharp-Studying/Part2 at main · NoNamed02/C-sharp-Studying

C#언어 공부 정리. Contribute to NoNamed02/C-sharp-Studying development by creating an account on GitHub.

github.com

 

 

'공부 > C#' 카테고리의 다른 글

C# 공부(9) 81~90  (0) 2024.08.26
C# 공부(8) 71~80  (0) 2024.08.26
C# 공부(6) 57~60  (0) 2024.08.25
C# 공부(5) 51~56 (Part 1 End)  (0) 2024.08.24
C# 공부(4) 41~50  (0) 2024.08.24