我正在编写一个用于在C#中计算SSTF算法的控制台程序。我没有为磁盘控制器或操作系统编写SSTF算法。在值添加到sum的最后几行中,编译器提供了有关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;
}
答案 0 :(得分:1)
可能存在永远不会为index
分配值的情况。
要使编译器满意,请指定一个默认值:
int index = -1;
如果你想正确处理它,你需要这样的东西:
if(index >= 0)
{
sum = sum + (key - tracks[index]);
tracks.RemoveAt(index);
}
else
{
// Show / log error ...
}