흐름 제어 - 코드 실행 순서를 결정하는 것

분기 - 제어 흐름을 여러 갈래로 나누는 것
         단, 프로그램은 한 번에 하나만 실행 가능

분기문1 : if


분기문2 : switch + break

int input = Convert.ToInt32(Console.ReadLine());

int score = (int)(Math.Truncate(input/10.0) * 10);
// 1의 자리 버림

string grade = "";

switch (score)
{
    case 90:
       grade = "A";
       break;
       
    case 80:
       grade = "B";
       break;
       
    case 70:
       grade = "C";
       break;
       
    case 60:
       grade = "D";
       break;
       
    default:
       grade = "F";
       break;
}

 

int input = Convert.ToInt32(Console.ReadLine());

int score = (int)(Math.Truncate(input/10.0) * 10);

string grade = score switch
{
    90 => "A",
    80 => "B",
    70 => "C",
    60 => "D",
    _ => "F"
};



반복문 1 : while
조건을 만족하는 동안 반복

반복문 2 : do while
코드 실행후, 조건을 평가하여 반복 수행

반복문 3 : for
조건을 만족하는 동안 반복(조건 변수 사용)

점프 : 흐름을 특정 위치로 단번에 이동
break, continue, goto, return, throw

break
반복문이나 switch문의 실행을 중단

continue
반복을 건너 뛰어 반복을 계속 수행

goto
지정한 레이블로 제어를 이동

패턴매칭
식이 특정패턴과 일치하는지를 검사

패턴매칭1 : 선언 패턴
주어진 식이 특정형식(int, string) 과 일치하는지를 평가

패턴매칭2 : 형식 패턴
선언 패턴과 거의 비슷하지만 변수를 선언하지 않는다.

패턴매칭3 : 상수 패턴
식이 특정 상수와 일치하는지를 검사

패턴매칭4 : 프로퍼티 패턴
식의 속성이나 필드가 패턴과 일치하는지를 검사

패턴매칭5 관계 패턴
관계 연사자를 이용하여 입력받은 식을 상수와 비교

패턴매칭6 :  논리패턴
복수의 패턴을 논리 연산자(and, or, not)로 조합

패턴매칭7 : 괄호패턴
괄호()로 패턴을 감쌈

패턴매칭8 : 위치 패턴
식의 결과를 분해하고, 분해된 값들이 내장된 복수의 패턴과 일치하는지 검사

패턴매칭9 : var 패턴
null을 포함한 모든 식의 패턴 매칭을 성공시키고, 그 식의 결과를 변수에 할당

패턴매칭10 : 무시 팬턴
var패턴처럼 모든 식과의 패턴 일치 검사를 성공
단, is식에서는 사용할 수 없고, switch식에서만 사용 가능

패턴매칭11 : 목록 패턴
배열이나 리스트가 패턴의 시퀀스가 일치하는지를 검사

 

using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20240226
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //int a = 1;
            //while(a== 2)
            //{
            //    Console.WriteLine("true");
            //}Console.WriteLine("false");

            //1. 구구단 출력하기: 사용자로부터 숫자를 입력받아 해당 숫자의 구구단을 출력하는 프로그램을 작성하세요.
            //for (int i = 1; i <= 9; i++)
            //{
            //    for(int j = 1; j <= 9; j++)
            //    {
            //        Console.WriteLine($"{i} * {j} = {i * j}");
            //    }
            //}


            //2. 숫자 맞히기 게임: 컴퓨터가 1에서 100 사이의 무작위 숫자를 선택하고, 사용자가 그 숫자를 맞히는 게임을 만드세요.사용자가 입력한 숫자가 정답보다 크면 "더 작은 수를 입력하세요"를, 작으면 "더 큰 수를 입력하세요"를 출력하세요. 정답을 맞힐 때까지 반복합니다.
            //Random random = new Random(); //Random 클래스 인스턴스 생성
            //int rand = random.Next(1, 101);// 1부터 100까지 난수 생성
            //Console.Write("숫자를 입력하세요. >> ");
            //int num = int.Parse(Console.ReadLine());
            //Console.WriteLine("컴퓨터가 입력한 숫자는 {0}입니다.", rand);
            //if (rand == num)
            //{
            //    Console.WriteLine("정답");
            //}
            //else Console.WriteLine("오답");



            //3. 짝수와 홀수 합계: 1에서 100까지의 모든 짝수와 홀수의 합을 구하는 프로그램을 작성하세요.
            //int odd = 0;
            //int even = 0;
            //for (int i = 1; i <= 100; i++)
            //{
            //    if(i % 2 != 0)
            //    {
            //        odd += i;
            //    }else if(i % 2 == 0)
            //    {
            //        even += i;
            //    }

            //}
            //Console.WriteLine(odd);
            //Console.WriteLine(even);

            //4. 사용자가 입력한 수의 팩토리얼 계산: 사용자로부터 정수를 입력받고, 그 수의 팩토리얼을 계산하여 출력하는 프로그램을 작성하세요.
            //int a = Convert.ToInt32(Console.ReadLine());
            //int factorialA = 1;
            //for(int i = 1; i <= a; i++)
            //{
            //    factorialA *= i;
            //}
            //Console.WriteLine(factorialA);
            //5. 세 수 중 최댓값 찾기: 사용자로부터 세 개의 숫자를 입력받고, 그 중 가장 큰 숫자를 출력하는 프로그램을 작성하세요.
            //int a = Convert.ToInt32(Console.ReadLine());
            //int b = Convert.ToInt32(Console.ReadLine());
            //int c = Convert.ToInt32(Console.ReadLine());
            //int maxNum = a;
            
            //if( b > maxNum)
            //{
            //    maxNum = b;
            //}
            //if( c > maxNum)
            //{
            //    maxNum = c;
            //}
            //Console.WriteLine("입력된 숫자중 가장 큰 수는 {0} 입니다. ", maxNum);
        }
    }
}

'낙서장 > C#' 카테고리의 다른 글

[C#] 메서드 오버로딩  (0) 2024.06.02
virtual ,override, base  (2) 2024.03.08
상속과 다형성  (1) 2024.03.08
데이터를 가공하는 연산자  (0) 2024.02.25
데이터를 담는 변수와 상수  (0) 2024.02.22

Shader "Custom/Triplanar"
{
    Properties
    {
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Top("Top", 2D) = "white" {}
        _Side("Side", 2D) = "white" {}
        _Front("Front", 2D) = "white" {}

    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }

        CGPROGRAM
        #pragma surface surf Lambert
        #pragma target 3.0

        sampler2D _MainTex;
        sampler2D _Top;
        sampler2D _Front;
        sampler2D _Side;

        struct Input
        {
            float2 uv_MainTex;
            float3 worldPos;
            float3 worldNormal;
            INTERNAL_DATA
        };

        void surf (Input IN, inout SurfaceOutput o)
        {
            //fixed4 c = tex2D (_MainTex, IN.uv_MainTex);

            float2 topUV = float2(IN.worldPos.x, IN.worldPos.z);
            float2 sideUV = float2(IN.worldPos.z, IN.worldPos.y);
            float2 frontUV = float2(IN.worldPos.x, IN.worldPos.y);




            float4 topColor = tex2D(_Top, topUV); // green = 1

            float4 sideColor = tex2D(_Side, sideUV); // red = 1

            float4 frontColor = tex2D(_Front, frontUV); // blue = 1

            //float3 n = WorldNormalVector(IN, o.Normal); //해당 면의 normal 벡터 => 값이 1이 된다.
            
            //혼합 lerp
            
            //float3 e = lerp(0, 1, topColor.g);
            //o.Emission = topColor.rgb;
            //o.Albedo = sideColor.rgb;
            //o.Emission = n.rgb;
            o.Albedo = lerp(topColor, frontColor,abs(IN.worldNormal.z));
            //위쪽 면의 색상과 앞면의 색상을 표면의 기울기에 따라 가중 평균화하여 새로운 색상을 생성
            //기울기가 높을수록 앞면의 색상이 더 많이 나타나며, 기울기가 낮을수록 위쪽 면의 색상이 더 많이 나타낸다.
            o.Albedo = lerp(o.Albedo, sideColor, abs(IN.worldNormal.x));
            o.Alpha = 1;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

 

 

그림과 같이 각 면이 해당하는 벡터를 확인한 후 색상을 집어 넣어야 한다.

 

Shader "Custom/Triplanar"
{
    Properties
    {
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Top("Top", 2D) = "white" {}
        _Side("Side", 2D) = "white" {}
        _Front("Front", 2D) = "white" {}

    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }

        CGPROGRAM
        #pragma surface surf Lambert
        #pragma target 3.0

        sampler2D _MainTex;
        sampler2D _Top;
        sampler2D _Front;
        sampler2D _Side;

        struct Input
        {
            float2 uv_MainTex;
            float3 worldPos;
            float3 worldNormal;
            INTERNAL_DATA
        };

        void surf (Input IN, inout SurfaceOutput o)
        {
            //fixed4 c = tex2D (_MainTex, IN.uv_MainTex);

            float2 topUV = float2(IN.worldPos.x, IN.worldPos.z);
            float2 sideUV = float2(IN.worldPos.z, IN.worldPos.y);
            float2 frontUV = float2(IN.worldPos.x, IN.worldPos.y);




            float4 topColor = tex2D(_Top, topUV); // green = 1

            float4 sideColor = tex2D(_Side, sideUV); // red = 1

            float4 frontColor = tex2D(_Front, frontUV); // blue = 1

            float3 n = WorldNormalVector(IN, o.Normal); //해당 면의 normal 벡터 => 값이 1이 된다.
            
            //혼합 lerp
            
            //float3 e = lerp(0, 1, topColor.g);
            //e = lerp (e, topColor.r, sideColor);
            //e = lerp (e, topColor.b, frontColor);
            //o.Emission = topColor.rgb;
            //o.Albedo = sideColor.rgb;
            o.Emission = n.rgb;
            //o.Albedo = lerp(topColor, frontColor,abs(IN.worldNormal.z));
            //위쪽 면의 색상과 앞면의 색상을 표면의 기울기에 따라 가중 평균화하여 새로운 색상을 생성
            //기울기가 높을수록 앞면의 색상이 더 많이 나타나며, 기울기가 낮을수록 위쪽 면의 색상이 더 많이 나타낸다.
            //o.Albedo = lerp(o.Albedo, sideColor, abs(IN.worldNormal.x));
            o.Alpha = 1;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

 

https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

 

Unity - Scripting API: Vector3.Lerp

Interpolates between the points a and b by the interpolant t. The parameter t is clamped to the range [0, 1]. This is most commonly used to find a point some fraction of the way along a line between two endpoints (e.g. to move an object gradually between t

docs.unity3d.com

 

'산대특 > 게임 UIUX 프로그래밍' 카테고리의 다른 글

Shader - Cubemap Reflection  (0) 2024.02.22
Shader - Diffuse Warping  (0) 2024.02.22
Shader -Blinn Phong 스펙큘러  (0) 2024.02.22
Shader - Lambert  (0) 2024.02.20
Shader - Vertex  (0) 2024.02.19

연산자란?

컴파일러에게 데이터 가공을 지시하는 신호

종류 : 산술 / 관계 / 논리 / 비트 /할당 / 기타 ...

 

증감 연산자 전위, 후위 연산자

int a = 10;
Console.WriteLine(++a);
// a = 11
int b = 10;
Console.WriteLine(b++);
// b = 10
Console.WriteLine(b++);
// b = 11

 

전위 연산자는 보기와 같이 기존에 정해진 값에서 더한 후 그 값을 출력

후위 연산자는 출력된 후 더하므로

다음 출력때 더해진 값을 출력

 

 

 

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20240223
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //사용자로부터 두 개의 숫자를 입력 받아 덧셈, 뺄셈, 곱셈, 나눗셈 연산을 수행하고 결과를 출력하는 프로그램을 작성하세요.
            //Console.WriteLine(10 + 5);
            //Console.WriteLine(10 - 5);
            //Console.WriteLine(10 * 5);
            //Console.WriteLine(10 / 5);


            //반지름을 입력 받아 원의 넓이를 계산하여 출력하는 프로그램을 작성하세요. (힌트: 원의 넓이 공식 - π * r * r)
            //int r = 5;
            //float circle = r * r * 3.14f;
            //Console.WriteLine(circle);

            //비교 연산자:
            //사용자로부터 두 개의 숫자를 입력 받아 두 숫자가 같은지 여부를 판단하여 결과를 출력하는 프로그램을 작성하세요.
            //Console.WriteLine(10 == 5);

            //사용자로부터 세 개의 숫자를 입력 받아 가장 큰 숫자를 출력하는 프로그램을 작성하세요.
            //int num1 = Convert.ToInt32(Console.ReadLine());
            //int num2 = Convert.ToInt32(Console.ReadLine());
            //int num3 = Convert.ToInt32(Console.ReadLine());
            //int maxNum = Math.Max(num1, Math.Max(num2, num3));
            //Console.WriteLine(maxNum);


            //논리 연산자:
            //사용자로부터 입력받은 숫자가 짝수인지 여부를 판단하여 결과를 출력하는 프로그램을 작성하세요.
            //int num = int.Parse(Console.ReadLine());
            //bool isEven = num % 2 == 0;
            //Console.WriteLine(isEven);


            //사용자로부터 입력받은 숫자가 3의 배수인지 그리고 5의 배수인지를 동시에 판단하여 결과를 출력하는 프로그램을 작성하세요.
            //int num = int.Parse(Console.ReadLine());
            //if(num % 15 == 0)
            //{
            //    Console.WriteLine("3과 5배 공배수");
            //}
            //else if(num % 3 == 0)
            //{
            //    Console.WriteLine("3의 배수입니다.");
            //}else if(num % 5 == 0){
            //    Console.WriteLine("5의 배수");
            //}
            //else {
            //    Console.WriteLine("다른 수");
            //}

            //대입 연산자:
            //사용자로부터 숫자를 입력 받아 그 숫자를 10배로 증가시킨 후 결과를 출력하는 프로그램을 작성하세요.
            //int number = Convert.ToInt32(Console.ReadLine());
            //int result = number * 10;
            //Console.WriteLine("Result: " + result);
            //두 변수의 값을 교환하는 프로그램을 작성하세요. (예: 변수 a에 5, 변수 b에 10이 있다면 a에는 10, b에는 5가 저장되어야 함)
            //int a = 10;
            //int b = 20;
            //int temp = a;
            //a = b;
            //b = temp;
            //Console.Write("a는 {0} b는 {1}", a, b);

        }

    }
}

'낙서장 > C#' 카테고리의 다른 글

[C#] 메서드 오버로딩  (0) 2024.06.02
virtual ,override, base  (2) 2024.03.08
상속과 다형성  (1) 2024.03.08
흐름 제어  (1) 2024.02.26
데이터를 담는 변수와 상수  (0) 2024.02.22

+ Recent posts