HackerRank - C语言11 Students Marks Sum 答案参考

#include 
#include 
#include 
#include 

//Complete the following function.
int marks_summation(int* marks, int number_of_students, char gender)
{
    int sum = 0;    //定义求和,整数型,初始化0
    
    if(gender == 'b'){      //判断:如果性别是b,boy
        for(int i = 0; i < number_of_students; i += 2)   //循环,0开始,代码里0就是第一位,因为题目说了男孩是第一个,女孩第二,男孩3,女孩4,依次类推,这样男孩间和女孩间都是相差2所以i+=2。判断条件里i当然是小于输入数量numberofstudent了
            sum += marks[i]; //求和变量循环相加赋值。配合题目后面给的mark指针malloc函数
    }
    else{       //如果不满足b,也就是输入的girl,从第二个开始,依次加2
        for(int i = 1; i < number_of_students; i += 2)
            sum += marks[i];
    }
    
    return sum;
}

int main()
{
    int number_of_students;
    char gender;
    int sum;
  
    scanf("%d", &number_of_students);
    int *marks = (int *) malloc(number_of_students * sizeof (int));
 
    for (int student = 0; student < number_of_students; student++) {
        scanf("%d", (marks + student));
    }
    
    scanf(" %c", &gender);
    sum = marks_summation(marks, number_of_students, gender);
    printf("%d", sum);
    free(marks);
 
    return 0;
}

你可能感兴趣的:(HackerRank - C语言11 Students Marks Sum 答案参考)