C#中循环可以使用while循环、for循环、do...while循环,其语法与C、C++相似。C#中特殊的循环是foreach循环,可用于遍历集合、数组中的元素。它的语法形式如下:
foreach (数据类型 变量名 in 集合名)
{
// 语句块
}
其中,数据类型是集合中元素的类型,变量名是用来存放每个元素的变量名,集合名是要遍历的集合。
以下是一个使用foreach循环计算数组中元素总和和平均值的示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//引用命名空间
namespace _2024_1_25 //项目名或命名空间
{
class Program //Program类
{
static void Main(string[] args) //Main函数是程序主入口
{
double[] points = { 1.2, 2.5, 3.7, 4.2, 5.0 };
double sum = 0.0;
foreach(double point in points)
{
sum += point;
}
Console.WriteLine(sum);
Console.ReadKey();
}
}
}
输出结果为16.6,是points数组中的各个数之和。