2 johnhuan JohnHuan 于 2017.05.20 12:31 提问

求各位大神帮我看一下代码关于“计算任意多个班级的学生的平均分”的问题,输入第二个分数就奔溃了。 5C

#include
#include
#include
#include
int main()
{
int nclasses = 0;

int nstudents_max = 0;

char answer = 'N';
printf("How many students are in the largest class? :");
scanf_s("%d", &nstudents_max);
printf("How many classes are there? :");
scanf_s("%d", &nclasses);

int **grades = (int**)malloc(nclasses * sizeof(int*));                //Stores the grades
int *students = (int*)malloc(nstudents_max * sizeof(int));            //Stores the number of students in each class

for (int nclass = 0; nclass < nclasses; ++nclass)
{
    printf("Enter the grades for students in class %d.\n", nclass + 1);
    students[nclass] = 0;                                                //Student count within a class
    while (true)
    {
        printf("Enter the integer grade for student %d: ", students[nclass] + 1);
        scanf_s("%d", &grades[nclass][students[nclass]]);
        if (++students[nclass] == nstudents_max)                            //Increment and check student count
        {
            printf("Class %d complete", nclass + 1);
            break;
        }
        printf("Any more students in class %d (Y or N): ", nclass + 1);
        scanf_s(" %c", &answer, 2);
        if (toupper(answer) == 'N')
            break;
    }
}

printf("\n");
for (int nclass = 0; nclass < nclasses; ++nclass)
{
    int class_tatal = 0;
    printf("Student grades for class %d are:\n", nclass + 1);
    for (int student = 0; student < students[nclass]; ++student)
    {
        class_tatal += grades[nclass][student];
        if ((student + 1) % 6 == 0)
            printf("\n");
        printf("%5d", grades[nclass][student]);
    }
    printf("\nAverge grade for class %d is %.2lf\n", nclass + 1, (double)class_tatal / students[nclass]);
}
return 0;

}

2个回答

qq_36742141
qq_36742141   2017.05.20 13:31

首先你程序就不对,逻辑上很多问题。至于你输入第二个分数就奔溃了,是因为数组越界了。你动态申请的内存空间就有问题,你申请了nclasses个一维数组指针,但只申请了一个一维数组。就算你申请了nclassed个一维数组,但这一句scanf_s("%d", &grades[nclass][students[nclass]]);也不对。

JohnHuan
JohnHuan   2017.05.21 10:06

初学者,麻烦大神帮忙改一下,谢谢!

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!