[Day9]C# 鸡础观念- 省去重复程序码的好帮手~for回圈

好烦好烦,有时候就为了1+2+..+100,
写了超长程序,
那又臭又长的程度堪比裹脚布啊。

for回圈/images/emoticon/emoticon71.gif

  • 在for回圈中,我们需要宣告一个初始值
  • 再来是宣告条件什麽时候该停下来
  • 以下是for回圈的结构
    https://ithelp.ithome.com.tw/upload/images/20210907/200970016wwyC09wTd.png

范例:我们来练习1+2+3+...+100

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CsharpDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //宣告一个整数,来让他自增
            int sum = 0;

            //开始使用for回圈
            for (int i = 1; i <= 100; i++)
            {
                sum += i;//使用指派运算子
            }

            //看结果
            Console.WriteLine(sum);
            Console.ReadKey();
        }
    }
 }

结果:

5050

随堂小练习 /images/emoticon/emoticon14.gif

范例:我们来用for回圈实现数学公式的阶乘,n!=1 X 2 X.....Xn

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CsharpDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //读取用户输入的数字
            int n = Convert.ToInt32(Console.ReadLine());

            //宣告一个长整数变数
            long a = 1;
            for (int i = 1; i <= n; i++)
            {
                //做乘法的累计
                a *= i;
            }
            Console.WriteLine(n + "! = " + a);
            Console.ReadKey();
        }
    }
  }

输入:

20

结果:

20
20! = 2432902008176640000

以上就是我们今天的for回圈,汇了回圈之後可以大大的降低程序的重复性,我们就明天再见啦!


<<:  AI 未来狂想

>>:  从 JavaScript 角度学 Python(9) - 容器型别(上)

企划实现(14)

GOOGLE登入 第八步:宣告 GoogleSignInClient mgoogleSignInCl...

[Day 15] 资料产品生命周期管理-预测模型

尽管都是模型,但预测模型目的在於预测未来,所以开发方式也会和描述型模型有所差异。 Initiatio...

DAY17 MongoDB Replication 观念

DAY17 MongoDB Replication 观念 本系列至今都是介绍 MongoDB 在单一...

追求JS小姊姊系列 Day10 -- 如果时间能重来,我不想跟工具人聊天(下)

前情提要 在D特的帮助下,试着穿越时空,但时间碎片凑齐了却还是出不去,现在该怎办? 我:...所以我...

AE卷轴制作4-Day5

在动画做好之後,因为这个卷轴的做法是分段, 做等速动态,所以今天想调整他的节奏分段做不容易, 所以教...