This program is supposed to have the user input a positive value including zero, tally valid and invalid(-2 or less) numbers, then find the average of the valid numbers. -1 is used as a sentinel value. The problem I'm having is that when I put in a invalid number it will work, but put in another invalid number, it doesn't work. I might be wrong, but it seems that it is treating it as a valid number and just subtracting it from the total used to compute the average.
Code:
#include <stdio.h>
#include <stdlib.h>
void main (void) {
int num, sum, valid, invalid;
float avg;
num=0;
sum=0.0;
valid = 0;
invalid = 0;
printf("Please enter a positive value or -1 to terminate the program:");
scanf("%d", &num);
while (num!=-1) {
if (num<=-2) {
invalid++;
printf("\n%d is not a valid positive value!!\n", num);
printf("Please enter a positive value or -1 to terminate the program:");
scanf("%d", &num);
}
else {
sum=sum+num;
valid++;
}
printf("Please enter a positive value or -1 to terminate the program:");
scanf("%d", &num);
}
avg=sum/valid;
printf("sum=%d\n", sum);
printf("valid=%d\n", valid);
printf("invalid=%d\n", invalid);
printf("avg=%.2f\n", avg);
}
There might be better ways to do this but I hvae to use while, if, and else loops.