显示数字1到100的总和和平均值

时间:2015-08-01 00:49:20

标签: c#

我正在尝试用C#编写一个简单的程序来显示数字1到100的总和和平均值。输出应该看起来像......

the sum is 5050
the average is 50.5

我似乎无法让它正常工作,返回值只返回总和而不是之前的措辞,我已经尝试了其他方式来显示消息和总和但是它们不起作用。我试图使用模型视图视图控制器方法,但无法理解我出错的地方以及如何让它显示上述结果。我的代码如下。

class SumAndAverage
{
    public float sum = 0;
    public float ave = 0;


    public float SumAndAve()
    {

        for (int i = 1; i <= 100; i++)
        {
            sum = sum + i;
            ave = sum / i;
        }

        return sum + ave;

    }

}

}

class SumAndAverageController
{
    IView view;
    SumAndAverage sumAndAverage;
    public SumAndAverageController(IView theView, SumAndAverage theSumAndAverage){
    view = theView;
    sumAndAverage = theSumAndAverage;
}
    public void Go()
    {
        view.Start();
        //mAndAverage.SetNumber(view.GetString("Please enter a number"));
        view.Show(sumAndAverage.SumAndAve());
        //view.Show(sumAndAverage.Result());
        view.Stop();
    }
}


class ConsoleView : IView
{
    public void Start()
    {
        Console.Clear();
    }

    public void Stop()
    {
        Console.WriteLine("Press any key to continue");
        Console.ReadKey();
    }



    public void Show<T>(T message)
    {
        Console.WriteLine(message);
    }

}


interface IView
{
    void Start();
    void Stop();
    void Show<T>(T message);
}


class Program
{
    static void Main(string[] args)
    {

        new SumAndAverageController(new ConsoleView(), new SumAndAverage()).Go();
    }
}

1 个答案:

答案 0 :(得分:7)

using System;
using System.Linq;

namespace SumAndAverage
{
    class Program
    {
        static void Main(string[] args)
        {
            var data = Enumerable.Range(1, 100);
            Console.WriteLine("the sum is " + data.Sum());
            Console.WriteLine("the average is " + data.Average());
        }
    }
}