写一方法用来计算1+2+3+...n,其中n作为参数输入,返回值可以由方法名返回,也可以由参数返回

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ConsoleApplication9
 8 {
 9     class Program
10     {
11         // 写一方法用来计算1+2+3+...n,其中n作为参数输入,返回值可以由方法名返回,也可以由参数返回
12         static void Main(string[] args)
13         {
14 
15            
16             do
17             {
18                 Console.WriteLine("计算1+2+3+...n,请输入n值");
19                 try
20                 {
21                     int n = Convert.ToInt32(Console.ReadLine());
22                     if (n >= 0)
23                     {
24                         Console.WriteLine("累加值为:{0}", sum(n));
25                         Console.ReadKey();
26                         return;
27                     }
28                     else
29                     {
30                         Console.WriteLine("========请输入非负整数========");
31                         Console.WriteLine();
32                     }
33                 }
34                 catch
35                 {
36                     Console.WriteLine("-------请输入整数-------");
37                     Console.WriteLine();
38                 }
39             } while (true);
40 
41         }
42 
43         static int sum(int n)
44         {
45             int sum=0;
46             for (int i = 0; i <= n; i++)
47             {
48                 sum += i;
49             }
50             return sum;
51         }
52 
53     }
54 }
原文地址:https://www.cnblogs.com/start-from-scratch/p/5061681.html