Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+21 votes

How do we get "average was" when a negative number is inputted?

asked in CSC211_Winter2018 by (1 point)

2 Answers

+13 votes

The total number accumulated that you use in the average should end when a negative number is typed in.

So you should have a while loop that checks to see if the number entered is not a negative and only add those numbers to your accumulating variable. And then, once a negative number is entered you take the average of the accumulated variable and the number of positive numbers.

answered by (1 point)
+11 votes

If you are just trying to get the string you emphasized, "average was", to display, you would use a print statement when the while loop is over.

To calculate the average, but not include the negative number used to end the loop, you would utilize something called the sentinel loop.

A sentinel loop is a loop that repeats until a sentinel value is seen.
A sentinel value is a value that signals the end of user input.

In this case, the sentinel value would be the negative number that the user inputs. The loop then should end when the sentinel value is inputted.

Remember to set up a sentinel loop:
1. Initialize and declare variable values outside of the while loop. Including the prompt for the value.
2. Start the loop and do all the computations.
3. Call / prompt for values again.

By setting up the loop this way, the loop will not run if the first value entered is a sentinel value or the loop will stop run immediately when the sentinel value is entered, which lets the computations happen while disregarding the sentinel value.

answered by (1 point)
...