average program(wikibooks exercise.)

Write a program that asks the user to type a positive integer. When the user types a negative value the program writes ERROR and asks for another value. When the user types 0, that means that the last value has been typed and the program must write the average of the positive integers. If the number of typed values is zero the program writes 'NO AVERAGE'.







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
47


#include<iostream>
using namespace std;

int main() {
    
     
int x, sum = 0,max = 0;
double average;
 
do{
  cout<<"Type an integer:";
  
  cin>>x;
  
  if (x > 0 ) {
  sum += x; max++;
}
  
else if(x<0)  cout << "ERROR "; 
 
 
  }while(x!=0);
 
if(max == 0)

cout << "NO AVERAGE"<<endl;

else {
     average = sum / max;
     
     cout<<"The average is : "<<average<<endl;
     }






system("pause");
return 0;
}






this program works.



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
47

#include<iostream>
using namespace std;

int main() {
    
     
int x, sum = 0,max = 0;
double average;
 
do{
  cout<<"Type an integer:";
  
  cin>>x;
  
 sum += x; max++;
  
 if(x<0)  cout << "ERROR "; 
 
 
  }while(x!=0);
 
if(max == 0)

cout << "NO AVERAGE"<<endl;

else {
     average = sum / max;
     
     cout<<"The average is : "<<average<<endl;
     }









system("pause");
return 0;
}





this program doesn't.


and I don't really get it because the only difference are:


1
2
3
4
5
6
7

sum += x; max++;
  
 if(x<0)  cout << "ERROR "; 
 



and

1
2
3
4
5
6
7
8
9

if (x > 0 ) {
  sum += x; max++;
}
  
else if(x<0)  cout << "ERROR "; 





WHY? I know that C++ is kind of picky but I don't get it.What makes ONE work,while the other one don't?
when doing else you need {} around that else statement. and you know not to use system functions right?
In this program, max is used to count the number of positive inputs. In the working program, max is incremented only when a positive number is inputted, as it should. However, in the non-working program, max is incremented for each input, including negatives and the zero.

when doing else you need {} around that else statement

The brackets are only necessary when there's multiple statements in the else clause. In this case, there's only the one output statement.
Last edited on
Topic archived. No new replies allowed.