Varied Amount of input data

Currently working on a lab that requires me to make a program that takes any number of non-negative integers as input, and outputs the maximum value and average of that input. So "15 20 0 5 -1" becomes "20 10".

I've gotten pretty far. This program does mostly do that, but it has the issue of entering something like "5 -1", where I don't know how to calculate the maximum value if there's nothing to compare it to.

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
#include <iostream>
using namespace std;
int main() {
int input;
int sum = 0;

cin >> input;

int count = 0;

int max = 0;

while (input >= 0) {
   sum = sum + input;
   cin >> input;
   count = count + 1;
 if (input >= max) {
  max = input;
 }
}


cout << max << " ";

cout << (sum / count) << endl;


return 0;

}


I've been trying different variations on if (input < max)or if (input < 0), but it's only messed other things up and almost certainly isn't what's being asked of me. I'm genuinely clueless here.
You could set max to input on line 11.
> int max = 0;
Try
int max = input;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main() {
	int sum {};
	int count {};
	int max {};

	cout << "Enter positive integer numbers to be processed. -1 to terminate: ";
	for (int input; (cin >> input) && (input >= 0); ++count, sum += input)
		if (input > max)
			max = input;

	cout << "Max is " << max << "\nAverage is " << (sum + 0.0) / count << '\n';
}



Enter positive integer numbers to be processed. -1 to terminate: 15 20 0 5 -1
Max is 20
Average is 10

Enter positive integer numbers to be processed. -1 to terminate: 5 -1
Max is 5
Average is 5


Last edited on
max = input worked, thank you!
Topic archived. No new replies allowed.