How to calculate the average using a while loop in the C programming language?
To find the average of a set of numbers using a while loop, you can follow these steps:
- Declare and initialize variables sum and count to 0, which will be used to calculate the total sum and count.
- Use a while loop to retrieve a set of numbers, and exit the loop when the input number is 0.
- In the loop, each time a number is input, the number is added to sum and count is incremented by 1.
- After the loop ends, calculate the average as average = sum / count.
- Output the average.
Here is a sample code:
#include <stdio.h>
int main() {
int num, sum = 0, count = 0;
float average;
printf("请输入一组数(以0结束):\n");
while (1) {
scanf("%d", &num);
if (num == 0) {
break;
}
sum += num;
count++;
}
average = (float)sum / count;
printf("平均数为:%.2f\n", average);
return 0;
}
In the above example, use a while loop to obtain a set of numbers, exiting the loop when the input number is 0. Within the loop, each time a number is input, add that number to the sum variable and increment count by 1. After the loop ends, calculate the average number by dividing sum by count, and output the result. Note, in order to obtain a floating point average, it is necessary to force convert sum to a float type.