显示数字1到100的和和平均值
本文关键字:平均值 数字 显示 | 更新日期: 2023-09-27 18:06:01
我正试图用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();
}
}
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());
}
}
}