Topic Collection of Zhejiang University Edition "C Language Programming (3rd Edition)"
Exercise 3-3 Count the average score and the number of passing students (15 points)
This question requires writing a program to calculate the average grade of the students and count the number of passers (with a score of not less than 60 points). The question guarantees that the input and output are within the integer range.
Input format:
Enter a non-negative integer N in the first line, which is the number of students. The second line gives N non-negative integers, that is, the scores of these N students, separated by spaces.
Output format:
Output in the following format:
average = average score
count = number of passing
The average value is accurate to one decimal place.
Input sample:
5
77 54 92 73 60Sample output:
average = 71.2
count = 4
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int N;
int count=0,sum=0;
double P;
scanf("%d\n",&N);
for (int i=0; i<N; i++)
{
int a;
scanf("%d",&a);
if(a>=60)
{
count ++;
}
sum=sum+a;
}
P= N==0? 0: sum*1.0/N;
printf("average = %.1f\n",P);
printf("count = %d",count);
}
Submit result:
to sum up:
- The ternary operator can be used to simplify the code, but in this question there must be a parameter to receive the result of the program, as shown below
P= N==0? 0: sum*1.0/N;
The following method cannot be used directly, otherwise an error will occur.
N==0? 0: sum*1.0/N;
2. Pay attention to the output format.