尝试构建结构的基本问题

A basic question trying to make a structure

我想做的是以结构数组的形式获取学生的姓名和三门科目的分数,并打印他们的姓名和平均分数。

我的错误在哪里?

#include <stdio.h>

typedef struct
{
    char name[5];
    int Kor; //yeah the three subjects
    int Eng;
    int Math;
}data;

double avg(int a, int b, int c) //to get the average
{
    double m;
    m = (a + b + c) / 3;
    return m;
}

int main()
{
    data group[3];
    for (int i = 0; i < 3; i++)
    {
        scanf("%s %d %d %d", group[i].name, group[i].Kor, group[i].Eng, group[i].Math);
    }
    for (int j = 0; j < 3; j++)
    {
        printf("%s %lf\n", group[j].name, avg(group[j].Kor, group[j].Eng, group[j].Math));
    }


 return 0;
}

我更改了scanf,'&'运算符用于访问内存位置中的地址。 scanf("%d",&a) 表示从键盘输入的值必须存储在内存 LOCATION 中,其名称为 'a'.

并更改平均值的 calculating function,因为您使用的是 operator/ 的整数除法版本,它需要 2 个整数和 returns 一个整数。为了使用 double 版本,returns double,至少有一个整数必须转换为 double。

#include <stdio.h>


typedef struct
{
    char name[5];
    int Kor; //yeah the three subjects
    int Eng;
    int Math;
}data;

double avg(int a, int b, int c) //to get the average
{
    double m;
    m = (a + b + c) / 3.0;
    return m;
}

int main()
{
    data group[3];
    for (int i = 0; i < 3; i++)
    {
        printf("enter your name ,Kor grade ,Eng grade ,Math grade\n");
        scanf("%s %d  %d %d", group[i].name, &group[i].Kor, &group[i].Eng, &group[i].Math);
    }
    for (int j = 0; j < 3; j++)
    {
        printf("name:%s avg:%lf\n", group[j].name, avg(group[j].Kor, group[j].Eng, group[j].Math));
    }


 return 0;
}

您应该确定并做的一件事是在 上使用 most/all 编译器警告标志进行编译。在你的例子中,当我用 GCC 编译你的程序时,使用标志 -W -Wall -Wextra,我 got 以下警告:

<source>: In function 'main':
<source>:23:20: warning: format '%d' expects argument of type 'int *', but argument 3 has type 'int' [-Wformat=]

   23 |         scanf("%s %d %d %d", group[i].name, group[i].Kor, group[i].Eng, group[i].Math);

      |                   ~^                        ~~~~~~~~~~~~

      |                    |                                |

      |                    int *                            int

以及 group[i].Enggroup[i].Math 的相同警告。

这些编译器警告通常实际上是您的错误,这些错误在运行时会导致程序崩溃或产生垃圾。在您的情况下,您需要传递要从输入中读取的值的 地址

这并不意味着这是您的代码的唯一问题,但在询问 us帮助。