0

我创建了带有属性和属性的 Car 类。在程序的主要部分,我创建了一系列汽车并初始化了这些值。

我的程序应该使用全局方法找到最快的汽车和所有汽车的平均速度,该方法还必须返回两个结果。

我试着做这个方法,我做了一个循环,它将单独通过每个速度,并将它与连续汽车的总数分开,然后添加到变量平均值,这有意义吗?

为了连续找到最快的车,我不知道该怎么做,所以我问了自己这个问题。

如果我在同一方法的定义中犯了错误,任何人都可以向我解释这种全局方法中的速度查找算法以及整个任务吗?

class Car
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private int price;

    public int Price
    {
        get { return price; }
        set { price = value; }
    }

    private float speed;

    public float Speed
    {
        get { return speed; }
        set { speed = value; }
    }    
}

这是主程序

class Program
{
    public static void MaxSpeedCarAverage(Car[] arraycar,float Maxspeed,float average)
    {                
        for(int i=0;i<10;i++)
        {
            average+= arraycar[i].Speed / 10;
        }
    }

    static void Main(string[] args)
    {
        Car[] car = new Car[10]
        {
            new Car(){Name="Bmw",Price=5888,Speed=290 },     //initialisation of array//
            new Car(){Name="Mercedes",Price=7544,Speed=300},
            new Car(){Name="Peugeot",Price=4500,Speed=190},
            new Car(){Name="Renault",Price=6784,Speed=210},
            new Car(){Name="Fiat",Price=3221,Speed=180},
            new Car(){Name="Audi",Price=4500,Speed=240},
            new Car(){Name="Golf",Price=4500,Speed=255},
            new Car(){Name="Sab",Price=4500,Speed=332},
            new Car(){Name="Range Rover",Price=4500,Speed=340},
            new Car(){Name="Honda",Price=4500,Speed=267},

        };

    }
}
4

3 回答 3

0

除非性能很关键,否则执行多个步骤就可以了:

a) find the maximum speed (hint: you can use .Select(..) and .Max( ) from System.Linq)
b) then find the car (s) that have that speed (.Where(...))
c) calculating the average can likewise been done using .Select( ) and .Average( )

是的,原则上您可以在一个手写循环中完成所有操作,但要以可读性/可维护性为代价。

于 2017-11-15T19:36:50.127 回答
0

尽管在这种情况下采用每个速度并除以 10 是可行的,但您可以考虑除以 Car 数组的长度而不是 10(在下面的代码示例中完成)。要找到最大速度,只需将数组中第一辆车的速度分配给最大速度,如果另一辆车更快,则更新它。

    public static void MaxSpeedCarAverage(Car[] arraycar, float maxspeed, float average)
    {
        maxspeed = arraycar[0].Speed;
        for(int i=0;i<10;i++)
        {
            if(arraycar[i].Speed > maxspeed) {
                maxspeed = arraycar[i].Speed;
            }
            average+= arraycar[i].Speed / arraycar.Length;
        }
    }
于 2017-11-15T19:38:27.740 回答
0

你应该像这样简化你的类:

public class Car {
    public string Name { get; set; }
    public double Price { get; set; }
    public double Speed { get; set; }
}

要返回两个结果,您可以返回 aTuple或通过引用传递参数

public static void GetMaxAndAverageFromCars(IEnumerable<Car> cars, ref double maxSpeed, ref double avgSpeed) {
    maxSpeed = cars.Max(c => c.Speed);
    avgSpeed = cars.Average(c => c.Speed);
}

像这样使用:

using System.Linq;

var cars = new Car[]
{
    // ..
};

double maxSpeed = 0.0;
double avgSpeed = 0.0;

GetMaxAndAverageFromCars(cars, ref maxSpeed, ref avgSpeed);
于 2017-11-15T19:41:59.807 回答