Unity的C#编程教程_38_循环语句挑战:打印单双数

  • 任务:计数打印从0~10,然后打印出 10~ 20 之间的双数,20~30之间的单数
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PrintNum : MonoBehaviour
{
    private int num = 0; // 初始化为 0

    // Start is called before the first frame update
    void Start()
    {
        while (num < 31) // 0~30 循环
        {
            if (num <= 10) // 10 以下都打印
            {
                Debug.Log("Num = " + num);
            }
            else if (num <= 20)
            {
                if (num % 2 == 0) // 判断为双数
                {
                    Debug.Log("Even Num = " + num);
                }
            }
            else
            {
                if (num % 2 == 1) // 判断为单数
                {
                    Debug.Log("Odd Num = " + num);
                }
            }

            num++;
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

Tags: