본문 바로가기
game as a service

유니티 연습 2 : 배열

by jessicahan96 2020. 12. 27.

1. 배열 사용하기

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int[] array = new int[5];
        array[0] = 2;
        array[1] = 10;
        array[2] = 5;
        array[3] = 15;
        array[4] = 3;

        //int[] array = {2, 10, 5, 15, 3};

        for (int i = 0; i < 5; i++)
        {
            Debug.Log(array[i]);
        }

    }
}

실행결과

2. 조건을 만족하는 요소만 출력하기

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int[] points = { 83, 99, 52, 93, 15};

        for (int i = 0; i < points.Length; i++)
        {
            if (points[i] >= 90)
            {
                Debug.Log(points[i]);
            }
        }

    }
}

실행결과

3. 평균값 구하기

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int[] points = { 83, 99, 52, 93, 15};
        int sum = 0;

        for (int i = 0; i < points.Length; i++)
        {
            sum += points[i];
        }
        float average = 1.0f * sum / points.Length;
        Debug.Log(average);

    }
}

실행 결과