首页 > 其他 > 详细

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

时间:2015-12-20 20:53:48      阅读:443      评论:0      收藏:0      [点我收藏+]
 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 }

 

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

原文:http://www.cnblogs.com/start-from-scratch/p/5061681.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!