zoukankan      html  css  js  c++  java
  • 写一方法用来计算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 }
  • 相关阅读:
    C#之设计模式
    C#之索引器
    C#基础强化-继承与多态
    C#基础强化-进程操作
    WKWebView与JavaScript交互基础
    HTML之JS学习
    HTML之CSS学习
    HTML学习
    玩诈欺的小杉
    最大异或和
  • 原文地址:https://www.cnblogs.com/start-from-scratch/p/5061681.html
Copyright © 2011-2022 走看看