【问题标题】:computing of sstf algorithm in console with c#使用 c# 在控制台中计算 sstf 算法
【发布时间】:2014-12-11 13:21:06
【问题描述】:

我正在编写一个控制台程序,用于在 C# 中计算 SSTF 算法。我不会为磁盘控制器或操作系统编写 SSTF 算法。在值相加的最后几行中,编译器给出了关于 index 变量的错误,因此我在 while 循环之前声明了 index 变量,但编译器仍然报告错误。

static void Main(string[] args)
{
    List<int> tracks = new List<int>();
    Console.WriteLine(" enter the current track");
    int key = Convert.ToInt32 (Console.ReadLine());

    Console.WriteLine("enter the tracks's number and -1 to end.");
    int track = Convert.ToInt32(Console.ReadLine());
    while(track != -1)
    {  
        tracks.Add(Convert.ToInt32(track));
        track = Convert.ToInt32(Console.ReadLine());
    }
    int sum=0;
    int count_of_tracks = tracks.Count;
    int distance;
    int minmum;
    int first;
    int index;

    while (tracks.Count != 0)
    {
        first = tracks[0];

        if (key > first)
            minmum = key - first;

        else
            minmum = first - key;

        for (int j = 1; j <= count_of_tracks; j++)
        {
            if (key > tracks[j])
            {
                distance = key - tracks[j];

                if (minmum > distance)
                {
                    minmum = distance;
                    index = j;
                }
            }
            if (key < tracks[j])
            {
                distance = tracks[j] - key;

                if (minmum > distance)
                {
                    minmum = distance;
                    index = j;
                }
            }
        }

        sum = sum + (key - tracks[index]);
        tracks.RemoveAt(index);
    }

    int seek_time = sum / count_of_tracks;        
}

【问题讨论】:

  • 为了完整起见:您能否在问题中包含编译器错误消息?

标签: c# algorithm disk


【解决方案1】:

可能存在从未为index 赋值的情况。 为了让编译器满意,请分配一个默认值:

int index = -1;

如果你想正确处理它,你需要这样的东西:

if(index >= 0)
{
    sum = sum + (key - tracks[index]);
    tracks.RemoveAt(index);
}
else
{
    // Show / log error ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多