Crash! Program to count and average odds and evens crashes...

My program compiles and runs correctly to count and average the number of odds and evens input by a user, but if I either don't enter any evens or don't enter any odds it crashes! Can anyone help me see why and how to fix it? Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
using namespace std;
int even=0;
int odd=0;
int number=0;
int main()
{
	int eventotal = 0; 
	int oddtotal = 0;
do
{
	cout << "Please enter a number: "<< endl;        
	cin >> number;   
	if ( (number%2 == 0) && (number > 0) )  
		{
             even++;
             eventotal = eventotal + number;
		}
	else if (number > 0) 
		{
			odd++;
            oddtotal = oddtotal +number;}
		}
while (number!=0);

int oddavg ;// to store the average of odd numbers  
oddavg = oddtotal/ odd;
int evenavg; // to store the average of even numbers
evenavg = eventotal / even;		    
//do
//{
//	cout << "Please enter a number: "<< endl;        
//	cin >> number;   
//	if ( (number%2 == 0) && (number > 0) )  
//		even++;
//	else if (number > 0) 
//		odd++;
//}
//while (number!=0);	
	
	cout << "You have entered" << ' '<< odd << ' ' <<"odd numbers." << endl;
	cout << "And" << ' ' << even << ' ' <<"even numbers." << endl;	
	cout << "Odd Average: " << oddavg << "." << endl;  
	cout << "Even Average: " << evenavg << "." << endl;
	
	return 0;}
That's because you divide by zero if you don't enter any even or any odd numbers (line 27 and line 29)

Make sure that eventotal or oddtotal is not equal to 0
1
2
3
4
5
if(oddtotal!=0)
    oddavg = oddtotal/ odd;
// ...
if(eventotal!=0)
    evenavg = eventotal / even;


and initialize oddavg and evenavg to 0
Last edited on
Duh! I should have seen that! Thank you so much! (Isn't it always the obvious things?)
Topic archived. No new replies allowed.