1:while循环
只要给定的条件为真 C#语言中的while循环语句会重复执行代码块的语句 语法如下
while(condition){ statement(s); }
测试代码如下
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test_8_5 : MonoBehaviour { void Start() { /* 局部变量定义 */ int a = 10; /* while 循环执行 */ while (a < 20) { Debug.Log("a 的值:" + a); a++; } } }
2:do while循环
for循环和while循环是在循环的头部判断循环条件,而do while循环是在循环的尾部判读循环条件,do while循环与while循环类似 但是do while循环会确保至少执行一次循环
do{
statement(s);
}
while(condition);
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test_8_6 : MonoBehaviour { void Start() { /* 局部变量定义 */ int a = 10; /* do 循环执行 */ do { Debug.Log("a 的值:" + a); a = a + 1; } while (a < 20); } }
3:for循环
for循环是一个特定次数的循环的重复控制结构
for(init;condition;increment){
statement(s);}
测试代码如下
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test_8_7 : MonoBehaviour { void Start() { /* for 循环执行 */ for (int a = 10; a < 20; a++) { Debug.Log("a 的值:" + a); } } }
4:foreach循环
C#语言也支持foreach循环,使用foreach循环可以迭代数组或一个集合对象
测试代码如下
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test_8_8 : MonoBehaviour { void Start() { // foreach循环 int[] fibarray = new int[] { 0, 8, 13 }; foreach (int element in fibarray) { Debug.Log(element); } // for 循环 for (int i = 0; i < fibarray.Length; i++) { Debug.Log(fibarray[i]); } // 设置集合中元素的计算器 int count = 0; foreach (int element in fibarray) { count += 1; Debug.Log("元素 #" + count + ":" + element); } Debug.Log("数组中元素的数量: " + count); } }
创作不易 觉得有帮助请点赞关注收藏~~~