任务是创建一个程序,允许用户输入学生姓名和成绩,列出所有输入,然后计算所有输入成绩的平均值。程序使用结构和循环。
我目前掌握的代码如下。它构建时没有任何错误。然而,在我输入第一组“名字、姓氏、年级”并按enter键后,程序只是坐在那里有一个闪烁的光标。我好像弄不明白我做错了什么。

#include <stdio.h>
#include <string.h>

#define MAX_LENGTH 50

// Structure to hold student names and grades
struct student
{
    char    firstName[MAX_LENGTH];
    char    lastName[MAX_LENGTH];
    int     grade;
};

int main ()
{
int i, j, num_students;
int sum = 0;
int cnt = 0;

// Determine how many students will be entered

printf ("Enter the number of students in your class: \n");
scanf ("%d", num_students);

// Obtain student names and grades
printf ("Enter first name, last name and grade separated by spaces. \n");
printf ("Enter END 0 when done entering information.\n\n");

struct student s[num_students];
for (i = 0; i < num_students; ++i) {

    scanf ("%s %s %d", s[i].firstName, s[i].lastName, s[i].grade);

    if(strcmp(s[i].firstName, "END") == 0) {
       break;
    }
}

// List students and grades entered
printf ("\nYou entered: \n");
for (j = 0; j < num_students; ++j){

    if(strcmp(s[j].firstName, "END") == 0){
        break;
    }
    printf("Name: %s %s, Grade: %d\n", s[i].firstName, s[i].lastName, s[i].grade);

}
// Calculate average of grades entered
for (i = 0; i < num_students; ++i)
{
    if (strncmp(s[i].firstName, "END", 3) == 0){
        break;
    }
    else {
        sum += s[i].grade;
        ++cnt;
    }
}

printf ("Average of Grades: %f\n", (float)sum/cnt);

return 0;
}

最佳答案

改变

printf("Name: %s %2, Grade: %d\n", s[i].firstName, s[i].lastName, &s[i].grade);
                  ^ Wrong specifier                                  ^ i should be j


printf("Name: %s %s, Grade: %d\n", s[j].firstName, s[j].lastName, s[j].grade);

关于c - C程序-不知道为什么它不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25395007/

10-11 22:23
查看更多