注册 登录
编程论坛 C语言论坛

求名位看看,循环那里出了什么问题,为什么else语句每次都会被执行,而且执行两遍

a187326700 发布于 2021-06-23 15:31, 1749 次点击
#include <stdio.h>
#include <string.h>
#define    CSIZE    4

struct    name{
    char    first[10];
    char    last[10];
};
struct    student{
    struct    name    names;
    float    grade[3];
    float    avge;
};

void Enter_grades(struct student *pt);//数据录入
void Per_aver(struct student *pt);//求平均值
void Show_value(struct student *pt);//输出
float Average(struct student *pt);//求总平均值
int    main(void)
{
    char    ch, *ans;
    struct student    stu_name[CSIZE];
    float    avge;
    puts("--------------------------------------");
    puts("d) Enter_grades           e) Per_aver");
    puts("f) Show_value             g) Average");
    puts("Please enter the menu options");
    puts("--------------------------------------");
    while((ch = getchar()) != NULL && ch != 'q' )
    {
        
        if(strchr("defg", ch))                                //这个地方哪里写的不对,为什么一执行就出3遍提示输出错误?
        {
            switch(ch)
            {
                case 'd':    Enter_grades(stu_name);    break;
                case 'e':     Per_aver(stu_name);        break;
                case 'f':     Show_value(stu_name);    break;
                case 'g':    avge = Average(stu_name);        break;
                default:        break;
            }
        }
        else        
            puts("Enter error, Please input ch:");               //这个语句每次都会被执行
    }   
    return    0;
}
void Enter_grades(struct student *pt)
{
    int i, j;
    for(i = 0; i < CSIZE; i++)
    {
        printf("please input the names[%d]:\n", i+1);
        gets(pt[i].names.first);
        gets(pt[i].names.last);
        puts("ipput the value");
        for(j = 0; j < 3; j++)
            scanf("%f", &pt[i].grade[j]);
    }
}
void Per_aver(struct student *pt)
{
    int i ,j;
    float total;
    for(i = 0; i < CSIZE; i++)
    {
        total = 0;
        for( j = 0; j < 3; j++)
            total += pt[i].grade[j];
        pt[i].avge = total / 3;
    }
    puts("平均分已求出");
}
float Average(struct student *pt)
{
    float    total;
    for(int i = 0; i < CSIZE; i++)
        total += pt[i].avge;
    return total/3;
}
void Show_value(struct student *pt)
{
    int i,j;
    for(i = 0; i < CSIZE; i++)
    {
        printf("%s %s\n",pt[i].names.first,pt[i].names.last);
        for(j = 0; j < 3; j++)
            printf("%.2f \t",pt[i].grade[j]);
        printf("\n%.2f\n", pt[i].avge);
    }
    printf("The total average score of the class is %.2f\n", Average);
}
求各位看看,哪里出了问题
2 回复
#2
rjsp2021-06-23 16:02
while((ch = getchar()) != NULL && ch != 'q' )
改为
while( scanf(" %c",&ch)==1 && ch!='q' )

getchar() 的返回类型是int,不是char,出错是返回EOF值,不是NULL

另外,printf("The total average score of the class is %.2f\n", Average); 我看不懂你想干什么,Average是个函数名。
#3
a1873267002021-06-23 16:06
哈,解决了,谢谢~!
另外,printf("The total average score of the class is %.2f\n", Average);我是想输出全班的平均分
1