Hello, I posted a while back, but it's been a while. I have learned a lot more, but ran into a problem today. I've been using a self teaching guide, and it gives you problems at the end of each chapter. Here is the problem I am working on:
3: Write a program that reads integers until 0 is entered. After input terminates, the program should report the total number of even integers (excluding the 0) entered, the average value of the even integers, the total number of odd integers entered, and the average value of the odd integers.
The program works, unless I enter a character. I know that C will store the character as a number, but do you know of a solution for this? Also, I can't use float type because of the % operand. What do you think?
Code:
#include<stdio.h>
#include<ctype.h>
#define EVEN 2
int main(void) {
int num;
int even, even_avg, odd, odd_avg;
even = even_avg = odd = odd_avg = 0;
printf("Enter some integers. Enter 0 to finish.\n");
while (scanf("%d", &num) == 1) {
/*if (isalpha(num)) {
printf("Invalid Entry. Please try again. %d\n", num);
continue;
}*/
if (num == 0)
break;
if ((num % EVEN) == 0) {
even++;
even_avg += num;
}
else {
odd++;
odd_avg += num;
}
}
printf("You have %d even %s, averaging %d.\n",
even, (even == 1) ? "number" : "numbers", even_avg / even);
printf("You have %d odd %s, averaging %d.\n",
odd, (odd == 1) ? "number" : "numbers", odd_avg/odd);
return 0;
}
It compiles fine. I use Cygwin and the compile it like this:
Code:
gcc -Wall -Werror -o file file.c