當前位置:編程學習大全網 - 編程軟體 - 從1加到100怎麽用計算機算

從1加到100怎麽用計算機算

1加到100的數式; n*(n-1)/2+n; 大家都知道從1加到100等於5050; 不妨用這個公式套壹下,看看等不等於5050;n就是從1加到第幾的數字; 100*(100-1)=9900; 9900/2=4950; 4950+100=5050; 看來這個公式是行的通的;所以當妳不會用for循環來寫的時候,就可以用這種公式的寫法了; 從1加到N的代碼:

using System;

using System.Collections.Generic;

using System.Text;

namespace ConsoleApplication1

{

public class Program

{

static void Main(string[] args)

{

int n, m, result;

string chars = "Y";

bool test;

do

{

Console.WriteLine("===============從1加到N的和===============");

Console.WriteLine("請輸入壹個數字!");

test = int.TryParse(Console.ReadLine(), out n);

if (test == true)

{

result = n * (n - 1) / 2 + n;

Console.WriteLine("和為:{0}", result);

Console.ReadLine();

}

else

{

Console.WriteLine("請不要輸入非法字符!");

chars = Console.ReadLine();

}

} while (chars == "N");

}

}

}

  • 上一篇:如何在網上創業
  • 下一篇:編寫姓名的程序
  • copyright 2024編程學習大全網