c - 使用结构在学生列表中找到最大的平均值

标签 c arrays function struct scanf

<分区>

问题是找到一组学生的最大平均值。如您所知,Structure 在这里起作用,在我看来,首先使用 Array of Structure 制作该结构是一个好主意(或者也许),因为我有 30 个学生。然后搜索该结构的成员并找到最终答案。

但我遇到了一个问题,我无法填充 struct Stdinfo student[stdnum] 并且我的 for 循环实际上无法正常工作,我不知道不知道为什么!

作为检查,我使用 printf() 打印其中一个成员,但我不能。

这是我的代码:

#include <stdio.h>

struct Stdinfo
{
    char name[30];
    int score;
};

struct Stdinfo function();

int main(int argc, char **argv)
{
    //Number of students ~stdnum
    int stdnum, i;
    puts("Input numbers of student(s) :");
    scanf("%i", &stdnum);
    stdnum--;

    struct Stdinfo student[stdnum];

    //Filling array of structure
    for (i = 0; i < stdnum; i++)
    {
        student[i] = function();
    }

    return 0;
}

struct Stdinfo function()
{
    struct Stdinfo student;
    puts("Input the name of the student : ");
    fgets(student.name, sizeof(student.name), stdin);
    puts("Input his(her) score:");
    scanf("%i", &student.score);
    return student;
}

现在搜索不是我的主要问题,我感谢任何帮助我解决“Structure's members filing”问题的帮助。

最佳答案

您错误地减小了数组的大小。这样做时,您将忽略最后一个学生。丢弃该减量。

现在想想输入是怎么来的。用户输入学生人数,然后回车!

scanf("%i",&stdnum); 将消耗数字,不会消耗换行符(来自 Enter)。

因此,fgets() 将读取该换行符并停在那里。换句话说,它认为这就是输入的实际内容。为了缓解这个问题,只需使用这个换行符,例如使用 getchar(),在调用 fgets() 之前。

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

struct Stdinfo{
        char name[30];
        int score;
    };

struct Stdinfo function() ;

int main(void)
{
    //Number of students ~stdnum
    int stdnum , i; 
    puts("Input numbers of student(s) :") ;
    scanf("%i" ,&stdnum);
    // Do not do that, it makes your program ignore the last student
    //stdnum--;

    struct Stdinfo student[stdnum]  ; 

    //Filling array of structure
    for(i=0 ; i < stdnum ; i++)
    {
        student[i] = function() ;
    }
    // print your array
    for(i=0 ; i < stdnum ; i++)
    {
        printf("%s\n", student[i].name);
        printf("%d\n", student[i].score);
    }

    return 0;
}

struct Stdinfo function() {

    struct Stdinfo student;

    getchar(); // Consume newline from previous input

    puts("Input the name of the student : ") ;
    fgets(student.name , sizeof (student.name) , stdin);
    // remove trailing newline from 'fgets()'
    student.name[strcspn(student.name, "\n")] = 0;

    puts("Input his(her) score:") ; 
    scanf("%i" ,&student.score) ;

    return student ; 
}

PS:你可能想要Removing trailing newline character from fgets() input (我的示例就是这样做的)。

关于c - 使用结构在学生列表中找到最大的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46360325/

相关文章:

c - 函数内部的 malloc 与 Main 中的 malloc

objective-c - Objective C 集合中的 C 风格指针

c - 类型定义一个枚举类型作为结构

c - 通过 20-30 GB 的多个日志文件搜索模式的最快方法是什么

javascript - 经典 asp - 由 vbscript 下拉列表填充的 javascript 数组

javascript - Coffeescript:从同一对象中的函数调用数组函数

c - 加载dll时访问冲突

php - PHP 是否优化数组类型的函数参数,而不是在未修改时通过引用显式传递?

java - 为什么 Java 中的完整数组在部分初始化时不打印?

javascript - 从模板创建 Javascript 对象