C#练习记录(请计算出一个整型数组的平均值。{ 1, 3, 5, 7, 90, 2, 4, 6, 8, 10 }。要求:计算结果如果有小数,则显示小数点后两位(四舍五入)。Math.Round())

题目:请计算出一个整型数组的平均值。{ 1, 3, 5, 7, 90, 2, 4, 6, 8, 10 }。要求:计算结果如果有小数,则显示小数点后两位(四舍五入)

代码实现:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    class Program
    {
        class Fa
        {
            public static void aver(int[] a1)
            {
                int sum = 0;
                for (int i = 0; i < a1.Length; i++)
                    sum += a1[i];
                Console.WriteLine("平均值为");
                Console.WriteLine("{0,8:F2}", Math.Round(Convert.ToDouble(sum / a1.Length)));//先转换为平均值,然后转换为double类型,然后使用math.round()函数进行四舍五入,输出时保留2位小数

            }
        }
        static void Main(string[] args)
        {
            int[] a = { 1, 3, 5, 7, 90, 2, 4, 6, 8, 10 };
            Fa.aver(a);
 
            Console.ReadKey();
        }
    }
}

  

 

posted @ 2017-10-20 22:37  功不唐捐,天道酬勤  阅读(821)  评论(0编辑  收藏  举报