大多数程序都可以工作,但我的数组并没有按照它应该的方式打印

时间:2016-10-07 18:04:10

标签: c arrays loops printf

我的数组没有打印出所有数据,只是最后输入的内容。数据应该打印出这样的东西 对于学号,如果输入的数字不够,则自动输入0。

/*
Name: 
Date: 10/06/2016
Workshop 4
*/
#include <stdio.h>

int main(void)
{
    int counter;
    int marks [40];
    float num_grades = 0;
    int row = 1;
    float sum = 0;
    float average = 0;
    int pass = 0;
    int fail = 0;
    float pass_sum = 0;
    float fail_sum = 0;
    float pass_average = 0;
    float fail_average = 0;
    float biggest = 0;
    float smallest = 0;

    //int grade[40];
    int student_num[40];

    printf("       ---=== IPC mark Analyser V2.0 ===---\n");

    printf("Please enter the number of students(between 3 and 40): ");
    scanf("%d", &counter);


    while (counter >40 || counter <3)
    {
        printf("Invalid number, enter a number between 3 and 40 inclusive: ");
        scanf("%d", &counter);

    }

    printf("Row   Std No Mrk\n");
    printf("--- --------- ---\n");

    num_grades = counter;
    while (counter > 0)
    {
        printf("%d ", row);
        printf("_____________ ___\r%3d ", row);
        scanf("%d", &student_num[40]);
        scanf("%d", &marks[40]);
        row++;
        counter--;
        sum += marks[40];
    }

    for (int i = 0; i < num_grades; i++)
    {
        printf("%03d %09d %3d\n", row, student_num[40], marks[40]);
    }


    average = sum / num_grades;

    printf("-----------------\n");
    printf("-----------------\n");
    printf("Marks Entered, printing results:\n");
    printf("Row   Std No Mrk\n");
    printf("--- --------- ---\n");


    printf("The average of all marks in this group is %.1f.\n", average);
    printf("Program Ended.\n");


    return 0;
}

1 个答案:

答案 0 :(得分:2)

您始终在student_nummarks数组中读/写索引40,因此所有内容都会转到同一位置。

实际上,大小为40的数组的有效索引是0到39,因此您实际上正在读取/写出数组的末尾,导致undefined behavior

您需要在每个地方使用正确的索引。在打印循环中,使用i。在阅读循环中,使用从0开始的变量上升到counter

num_grades = counter;
for (int i = 0; i < num_grades; i++)
{
    printf("%d ", i + 1);
    printf("_____________ ___\r%3d ", i + 1);
    scanf("%d", &student_num[i]);
    scanf("%d", &marks[i]);
    sum += marks[i];
}

for (int i = 0; i < num_grades; i++)
{
    printf("%03d %09d %3d\n", row, student_num[i], marks[i]);
}