本课目录

逐项累加

从零开始,每读到一个数就把它加到总数里。

简单示例

初始状态2 + 4
结果6
Program.cs
using System;

int total = 0;
total += 2;
total += 4;
Console.WriteLine(total);
输出
6
广告

生活中的例子

三个班分别捐了 5 本、2 本和 4 本书。图书馆一共能把多少本书放上书架?

初始状态5 + 2 + 4
结果11
Program.cs
using System;

int[] books = new int[] { 5, 2, 4 };
int total = 0;
int i = 0;
while (i < 3) {
    total += books[i];
    i += 1;
}
Console.WriteLine(total);
输出
11
运行示例
终端
dotnet new console --output Lesson
cp Program.cs Lesson/Program.cs
dotnet run --project Lesson
官方文档