207k views
1 vote
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the average and max. A negative integer ends the input and is not included in the statistics. Ex: When the input is 15 20 0 5 -1, the output is:

2 Answers

3 votes

Final answer:

To write a program that takes any number of non-negative integers as input and outputs the average and max, you can use a loop to continuously take input numbers until a negative number is entered.

Step-by-step explanation:

To write a program that takes any number of non-negative integers as input and outputs the average and max, you can use a loop to continuously take input numbers until a negative number is entered. Within the loop, keep track of the sum of the numbers and the maximum number encountered. After the loop ends, calculate the average by dividing the sum by the number of inputs.

Here is an example implementation in Python:

count = 0
sum = 0
max = None

while True:
num = int(input())
if num < 0:
break
count += 1
sum += num
if max is None or num > max:
max = num

average = sum / count

print('Average:', average)
print('Max:', max)

When this program is run with the input 15 20 0 5 -1, it will output:

Average: 10.0
Max: 20

User Jenny
by
4.9k points
5 votes

Final answer:

To calculate the average and maximum of a series of non-negative integers using a program.

Step-by-step explanation:

To write a program that calculates the average and maximum of a series of non-negative integers, we can use a loop to input the numbers one at a time. We'll keep track of the sum of the numbers and the maximum number so far. When a negative number is entered, we'll exit the loop and calculate the average by dividing the sum by the number of non-negative numbers entered. Here's an example program in Python:

sum = 0
max = float('-inf')
num = int(input())
count = 0

while num >= 0:
sum += num
if num > max:
max = num
count += 1
num = int(input())

if count > 0:
average = sum / count
print('Average:', average)
print('Max:', max)
else:
print('No non-negative numbers entered.')
User Romiem
by
4.9k points