This question requires writing a program to calculate 4
the sum and average of integers. The question guarantees that the input and output are within the integer range.
Input format:
Enter 4 integers in one line, separated by spaces.
Output format:
“Sum = 和; Average = 平均值”
Output the sum and average value in a row in the order of format , where the average value is accurate to one decimal place.
Input sample:
1 2 3 4
Sample output:
Sum = 10; Average = 2.5
Code:
# include <stdio.h>
# include <stdlib.h>
int main(){
int x1,x2,x3,x4,sum;
double average;
scanf("%d %d %d %d",&x1,&x2,&x3,&x4);
sum = x1 + x2 + x3 + x4;
average = sum / 4.0;
printf("Sum = %d; Average = %.1lf",sum,average);
return 0;
}
Submit screenshot:
Problem-solving ideas:
Note that average
when you get the final result , divide by 4.0
. Sometimes the front is an integer. Dividing by the back number will only get an integer, which is not the same as the result, so we have to construct a floating point number to make the result correct!