1

我为 FCFS 调度编写了以下代码。问题是这段代码编译得很好,但是执行./a.out后什么都没有显示,程序卡住了。它甚至不打印"Reading" printf开头的语句main()。问题是什么?

#include <stdio.h>

struct process
{

  int at;
  int bt;
  int wt;
  int tt;
  int rt;
  char pid[5];

} p[5];

int i, j;
int n = 0;

void main()
{
  printf("Reading");
  FILE *fp;
  fp = fopen("in1.txt", "r");
  char sample;
  if (fp != NULL )
  {
    sample = getc(fp);
    while (sample != EOF);
    {
      if (sample == '\n')
        n++;
      sample = getc(fp);
    }
    fseek(fp, 0, 0);
    for (i = 0; i < n; i++)
    {
      fscanf(fp, "%s %d %d", p[i].pid, &p[i].at, &p[i].bt);
      p[i].wt = p[i].tt = 0;
      p[i].rt = p[i].bt;
    }
    fclose(fp);
  }
  //sorta();
  printf("\nGantt Chart for FCFS\n");

  int t = 0;
  int avgw = 0;
  int avgt = 0;
  printf("%d ", t);
  for (i = 0; i < n; i++)
  {
    if (p[i].at > t)
    {
      printf("%d ", t);
      t = p[i].at;
    }
    p[i].wt = t - p[i].at;
    avgw = avgw + p[i].wt;
    printf("%s ", p[i].pid);
    p[i].tt = p[i].bt + p[i].wt;
    avgt = avgt + p[i].tt;
    t = t + p[i].bt;
    printf("%d ", t);
    printf("\navg waiting time = %d", avgw / n);
    printf("\navg turn around time = %d", avgt / n);
  }
}
4

2 回答 2

8

标准输出是行缓冲的。将“Reading”更改为“Reading\n”,您将看到它。

那么你这里有一个错误:

while (sample!=EOF);

该while循环的主体只是分号,而不是后面的块!如果条件为真,您的程序将陷入无限循环。

于 2013-06-28T06:03:31.360 回答
1

请在顶部写下以下语句,即之后void main

int t =0;
int avgw=0;
int avgt=0;

并删除;之后

 while (sample!=EOF)
于 2013-06-28T06:07:55.927 回答