我如何将当前var分配给else语句,以便能够比较var值,然后将其保存以得到结果?

问题描述 投票:0回答:1

我有一个If Else语句,要从当前位置中获得最近的位置,这意味着第一个位置为空(不存在),并且根据第一个位置的最小距离来计算第二个位置。在其他部分中,我将通过使用Math.Min将当前站点的距离与已知的最小距离进行比较。但是,我缺少在Else语句中存储结果和分配当前电台的功能。我的问题所在的位置是第14和15行。

class City : ICity
    {
        private List<Company> _companies;
        private List<Line> _lines;
        private List<Station> _stations;
        internal City(string name)
        {
            this.Name = name;
            _companies = new List<Company>();
            _lines = new List<Line>();
            _stations = new List<Station>();
        }
        public string Name{get;}
        public ILine AddLine(string name){...} 
        public IStation AddStation(string name, int x, int y){...}

        public IStation FindNearestStation(int x, int y)
        {
            int ? minDist = null;
            Station minStation=null;
            foreach (var station in _stations)
            {
                int dis = GetDistancebtween(x1: station.X, y1: station.Y, x2: x, y2: y);
                if (!minDist.HasValue || dis < minDist.Value)
                {
                    minDist = dis;
                    minStation = station;
                }
            }
            return minStation;            
        }

        private int GetDistancebtween(int x1, int y1, int x2, int y2)
        {
            return (x1 - x2) ^ 2 + (y1 - y2) ^ 2; 

        }            
}

单元测试在第10行中断。

public void city_returns_effectively_the_closest_station()
{
    ICity c = CityFactory.CreateCity("Paris");

    IStation s = c.AddStation("Opera", 0, 0);
    IStation s1 = c.AddStation("Chatelet", 10, 10);

    c.FindNearestStation(-10, -10).Should().BeSameAs(s);
    //test does not pass in this position
    c.FindNearestStation(10, 10).Should().BeSameAs(s1);
    c.FindNearestStation(15, 15).Should().BeSameAs(s1);
}
c# return-value variable-assignment store min
1个回答
0
投票

如果更改minDist值,则还应该更改minStation值。在else块内而不是Math.Min内使用简单的if可以解决问题。

....
else
{
    if(dis < minDist.Value)
    {
        minDist = dis;
        minStation = station;
    }
}

并且这将导致不使用else块而进行进一步的更改

foreach (var station in _stations)
{
    var dis = GetDistancebtween(x1: x, y1: y, x2: station.X, y2: station.Y);
    if(!minDist.HasValue || dis < minDist.Value)
    {
        minDist = dis;
        minStation = station;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.