0

我不明白这个错误告诉我什么。当我运行程序时,它应该不断循环,直到用户输入 N (不再/退出)。我不明白发生了什么事。在第一组输入之后,在提示用户“你想处理一个新学生”之前,程序会抛出该异常。

我已经使用 Geany(它没有给我任何它只是崩溃的错误定义)和 Visual Studio 2010 运行它。

有人可以帮忙吗?

void draw_bar_chart(int student_id[], int percentage[], int size)
{
    FILE *report;
    int i, j=0, min = 1000000, max = 0, min_pos, max_pos, l;
    char s[20];

    report = fopen("report2.txt", "a");
    fprintf(report, "\n******* BAR CHART (YEARLY TOTAL EXPENSES: YEARLY TOTAL INCOME) *******\n\n");      

    for (i = 0; i < size; i++)
    {
        fprintf(report, "%d%c", student_id[i], ' ');
        if (percentage[i] > 0){
            l = percentage[i]/10; //the lenght of the bar
            if ((percentage[i]%10) > 0)
                l++;
            for (j = 0; j < l; j++)
                s[j] = 'x';
            s[l+1] = '\0';
        } else {
            s[0] = '!';
            s[1] = '\0';
        }

        fprintf(report, "%-20s%6c%d%c\n", s, ' ', percentage[j], '%');

        if (percentage[j] >= 0)
        {
            if (percentage[j] < min)        
            {
                min = percentage[j];        
                min_pos = j;                
            }
            if (percentage[j] > max)    
            {
                max = percentage[j];        
                max_pos = j;                
            }
        }
    }


    fprintf(report, "***lowest percentage:  %d%c (student ID: %d)\n", min, '%', student_id[min_pos]);
    fprintf(report, "***highest percentage: %d%c (student ID: %d)\n", max, '%', student_id[max_pos]);

    fclose(report);

    }
4

1 回答 1

2

我可以看到以下错误:

  1. 它应该是 s[l] = '\0',而不是 s[l+1] = '\0'。
  2. 在 s 中写下横杠后,所有出现的 j 都必须替换为 i。
  3. min_pos 和 max_pos 可能未初始化。

真正的问题是第二个问题。您可以通过养成将变量放在尽可能小的范围内的习惯来避免这种错误。即你有没有写这个:

        ...
        fprintf(report, "%d%c", student_id[i], ' ');

        /* display percentage */
        {
          char s[20];

          if (percentage[i] > 0) {
            int l, j;

            l = percentage[i] / 10; // the length of the bar
            if ((percentage[i]%10) > 0)
                l++;
            for (j = 0; j < l; j++)
                s[j] = 'x';
            s[l] = '\0';
          }
          else {
            s[0] = '!';
            s[1] = '\0';
          }

          fprintf(report, "%-20s%6c%d%c\n", s, ' ', percentage[i], '%');
        }

        /* update min, max */
        if (percentage[i] >= 0) {
        ...

那么代码会更容易理解,如果你在 /* update ... */ 之后错误地使用 j 而不是 i,编译器会给你一个错误。更好的办法是将百分比显示位放在一个单独的函数中。

顺便说一句,格式字符串中不需要这些 %c ,只需将字符直接放入即可。% 可以用 %% 转义。

于 2012-08-05T17:04:22.593 回答