你的位置:首页 > ASP.net教程

[ASP.net教程]C#方法的练习


using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Demo1{  class Program  {    /// <summary>    /// 求一个字符串数组中最长的元素    /// </summary>    /// <param name="s"></param>    /// <returns></returns>    public static string GetLongest(string[] s)    {      string max = s[0];      for (int i = 0; i < s.Length; i++)      {        if (s[i].Length > max.Length)        {          max = s[i];        }      }      return max;    }    static void Main(string[] args)    {      //用方法来实现:有一个字符串数组:      //{"马龙","迈克尔乔丹","雷吉米勒","科比"},请输出最长的那个      string[] names = { "马龙", "迈克尔乔丹", "雷吉米勒", "科比" };      Console.WriteLine(GetLongest(names));    }  }}

 

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Demo1{  class sumnumber  {    /// <summary>    /// 计算出整数数组的平均值并保留2位小数    /// </summary>    /// <param name="nums"></param>    /// <returns></returns>    public double GetAvg(int[] nums)    {      double sum = 0;      for (int i = 0; i < nums.Length;i++ )      {        sum += nums[i];      }      return sum / nums.Length;    }  }}using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Demo1{  class Program  {      static void Main(string[] args)    {      int[] numbers = { 1, 2, 7 };      sumnumber sber = new sumnumber();      double avg = sber.GetAvg(numbers);      //保留2位小数 将avg转换成string类型      //然后用Convet.ToDouble转换      string str=avg.ToString("0.00");      avg = Convert.ToDouble(str);      Console.WriteLine(avg);      Console.ReadKey();    }  }}