909天 咸鱼也有梦想

重要的人越来越少,剩下的人也越来越重要 ​​

C#学习之三种方法求0-100的和

发布于 1年前 / 212 次围观 / 0 条评论 / C# / 咸鱼

1.for循环

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

namespace PropertySanple
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Calculator c = new Calculator();
            int result = c.SumFrom1ToX(100);
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }

    class Calculator
    {
 
        // for循环求0-100的和
        public int SumFrom1ToX(int x)
        {
            int result = 0;
            for (int i = 1; i < x+1; i++)
            {
                result = result + i;
            }
            return result;
        }

    }

}

2.递归

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

namespace PropertySanple
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Calculator c = new Calculator();
            int result = c.SumFrom1ToX(100);
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }

    class Calculator
    {
        //递归 0-100的和
        public int SumFrom1ToX(int x)
        {
            if(x == 1)
            {
                return x;
            }
            else
            {
                int result = x + SumFrom1ToX(x-1);
                return result;
            }
        }


    }


}

3.梯形求和的思路

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

namespace PropertySanple
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Calculator c = new Calculator();

            int result = c.SumFrom1ToX(100);
            Console.WriteLine(result);
            Console.ReadKey();

        //求梯形的思路
        public int SumFrom1ToX(int x)
        {

            return  (1 + x) * x / 2;
           

        }

    }


}