Hi there, so I made this program that ask users to enter a series of number and then the program will show the total number that the user entered, the sum and mean of the number. Below is my coding:
#include<stdio.h>
#include<stdlib.h>
#pragma warning (disable:4996)
#define SENTINEL -999
void main()
{
int n=0, i=0, sum = 0;
float mean = 0;
do {
printf("Give me any integer (-999 to stop): ");
scanf("%d", &n);
if (n != SENTINEL)
i += 1;
sum = sum + n;
mean = sum / i;
} while (n != SENTINEL);
printf("total number you has keyed in : %d\n", i);
printf("sum of the numbers: %d\n", sum);
printf("Mean of the numbers: %.3f\n", mean);
system("pause");
}
For the input, I put 2 and 4, so total number that I had keyed in is 2 and the sum is 6,while the mean is 3.000. However, the program gave me the wrong sum and mean.
I think there's problem with the sum and mean coding, any help will be appreciated and thank you for helping.
You need L15-16 within the body of the if statement. As it stands if n is the sentinel then sum also includes the sentinel. mean should be calculated once the loop has terminated.
#include <stdio.h>
#include <stdlib.h>
#pragma warning (disable:4996)
#define SENTINEL -999
void main()
{
int n = 0, i = 0;
float sum = 0;
do {
printf("Give me any integer (-999 to stop): ");
scanf("%d", &n);
if (n != SENTINEL) {
++i;
sum += n;
}
} while (n != SENTINEL);
printf("total number you has keyed in : %d\n", i);
printf("sum of the numbers: %.0f\n", sum);
printf("Mean of the numbers: %.3f\n", sum / i);
//system("pause");
}