正确的应输出最高最低分。以文本形式建立初始数据文件,文件名为,file1.dat,请输入十个学生的学号,姓名及考试成绩,读入file1.dat中的数据,输出最高分与最低分

正确的应输出最高最低分。以文本形式建立初始数据文件,文件名为,file1.dat,请输入十个学生的学号,姓名及考试成绩,读入file1.dat中的数据,输出最高分与最低分


 
#include <stdio.h>
#include <stdlib.h>
#define N 10
struct student
{
    int num;
    char name[20];
    int score;
};
int main()
{
    int i;
    student st, stmax, stmin;
    FILE* fp;
    stmax.score = 0;
    stmin.score = 100;
    fp = fopen("file1.dat", "r");
    if (!fp)
        exit(0);
    for (i = 0; i < N; i++)
    {
        fscanf(fp, "%d %s %d", &st.num, st.name, &st.score);
        if (st.score > stmax.score)
            stmax = st;
        if (st.score < stmin.score)
            stmin = st;
    }
    fclose(fp);
    printf("high:%5d%15s%5d\n", stmax.num, stmax.name, stmax.score);
    printf("low:%5d%15s%5d\n", stmin.num, stmin.name, stmin.score);
    return 0;
}

为什么我运行的结果是这样的

img

应该是你编译器没有设置好

或者
student st, stmax, stmin;
改成
struct student st, stmax, stmin;
看看, 有的编译器声明变量时struct不能省略

#include <stdio.h>
#include <stdlib.h>
#define N 10
struct student
{
    int num;
    char name[20];
    int score;
};
int main()
{
    int i;
    struct student st, stmax, stmin;//加上    struct
    FILE* fp;
    stmax.score = 0;
    stmin.score = 100;
    fp = fopen("file1.dat", "r");
    if (!fp)
        exit(0);
    for (i = 0; i < N; i++)
    {
        fscanf(fp, "%d %s %d", &st.num, st.name, &st.score);
        if (st.score > stmax.score)
            stmax = st;
        if (st.score < stmin.score)
            stmin = st;
    }
    fclose(fp);
    printf("high:%5d%15s%5d\n", stmax.num, stmax.name, stmax.score);
    printf("low:%5d%15s%5d\n", stmin.num, stmin.name, stmin.score);
    return 0;
}

或者改成这样

typedef struct
{
    int num;
    char name[20];
    int score;
} student;

就可以直接用 student st, stmax, stmin;


#include <stdio.h>
#include <stdlib.h>
#define N 10
typedef struct
{
    int num;
    char name[20];
    int score;
} student;
int main()
{
    int i;
    student st, stmax, stmin;
    FILE* fp;
    stmax.score = 0;
    stmin.score = 100;
    fp = fopen("file1.dat", "r");
    if (!fp)
        exit(0);
    for (i = 0; i < N; i++)
    {
        fscanf(fp, "%d %s %d", &st.num, st.name, &st.score);
        if (st.score > stmax.score)
            stmax = st;
        if (st.score < stmin.score)
            stmin = st;
    }
    fclose(fp);
    printf("high:%5d%15s%5d\n", stmax.num, stmax.name, stmax.score);
    printf("low:%5d%15s%5d\n", stmin.num, stmin.name, stmin.score);
    return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632