John欢 2017-05-20 04:31 采纳率: 0%
浏览 1180
已结题

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

#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条回答

  • 取个名字是真的难 2017-05-20 05:31
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog