无法打印预期结果

时间:2018-04-05 09:53:46

标签: c

问题: 奖学金有五种,奖学金数量没有限制,每个学生可以同时获得多项奖学金。我必须计算每个学生的奖学金。

我的代码是:

#include <stdio.h>

struct Student
{
    char name[21];
    int score1;
    int score2;
    char leader;
    char west;
    int paper;
    int sum;
};
int main(void)
{
    struct Student stu[100];
    int money_get(struct Student stu[],int m);
    int i,n;
    scanf("%d",&n);   //n is the number of student
    for(i=0;i<n;i++)  //input every student's information
    {
        scanf("%s %d %d %c %c %d",stu[i].name,&stu[i].score1,&stu[i].score2,&stu[i].leader,&stu[i].west,&stu[i].paper);
        stu[i].sum=money_get(&stu[i],i);
    }

    for(i=0;i<n;i++)    //output every student's name and their scholarship
        printf("%-21s%d\n",stu[i].name,stu[i].sum);
    return 0;
}

int money_get(struct Student stu[],int m)
{
    int money;
    money=0;

    //the conditons of the five scholarship

    if(stu[m].score1>85&&stu[m].score2>80)    
        money+=4000;
    if(stu[m].score1>80&&stu[m].paper>0)
        money+=8000;
    if(stu[m].score1>90)
        money+=2000;
    if(stu[m].score1>85&&stu[m].west=='Y')
        money+=1000;
    if(stu[m].score2>80&&stu[m].leader=='Y')
        money+=850;
    return money;
}

输入是:

4
Tom 87 82 Y N 0
Jack 88 78 N Y 1
Jane 92 88 N N 0
Bob 83 87 Y N 1

输出应该是:

Tom 4850
Jack 9000
Jane 6000
Bob 8850

但它是:

Tom 4850
Jack 0
Jane 2000
Bob 2000

它只适用于第一个学生。你能告诉我我哪里错了吗?

1 个答案:

答案 0 :(得分:2)

您的问题

您正在将&stu[i]传递给money_get()

stu[i].sum = money_get(&stu[i], i);

所以你将一个指向stu[i]的指针作为参数传递,但是在money_get()中,你stu[m] stu已经指向stu[i]

解决方案

  • money_get()只应将指向单个Student的指针作为参数。
  • 然后stu[m].可以替换为stu->

示例:

int money_get(struct Student *stu)
{
    int money = 0;

    if (stu->score1 > 85 && stu->score2 > 80)    
        money += 4000;
    if (stu->score1 > 80 && stu->paper > 0)
        money += 8000;
    if (stu->score1 > 90)
        money += 2000;
    if (stu->score1 > 85 && stu->west == 'Y')
        money += 1000;
    if (stu->score2 > 80 && stu->leader == 'Y')
        money += 850;
    return money;
}

您可以像这样调用此版本的money_get()

stu[i].sum = money_get(&stu[i]);