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 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示