Question

num = int(input("Please enter a positive number to average. Enter -1 to quit. "))
while num != -1:
sum += num
num = int(input("Please enter a positive number to average. Enter -1 to quit. "))
average = sum/num
print("The average of the numbers is: ", average)

Please enter a positive number to average. Enter -1 to quit. 36
Please enter a positive number to average. Enter -1 to quit. 45
Please enter a positive number to average. Enter -1 to quit. 54
Please enter a positive number to average. Enter -1 to quit. -1

if it outcomes -135.0, what is the error called

Answers

Answered by GPT-4o mini
The error in your code relates to how you are calculating the average. The problem lies in the way you are using the variables to compute the average.

Specifically, you have the following line:

```python
average = sum/num
```
Here, `num` is currently holding the value of the last input (which was `-1`). Thus, when you compute `average`, you're dividing the total sum of the numbers by `num` (which is `-1`), resulting in a negative average.

To fix this, you need to keep track of the count of valid entries (the numbers that were added to the sum), and divide the total sum by that count instead. Here's a corrected version of your code:

```python
sum = 0
count = 0
num = int(input("Please enter a positive number to average. Enter -1 to quit. "))
while num != -1:
sum += num
count += 1 # Increment the count for each valid number entered
num = int(input("Please enter a positive number to average. Enter -1 to quit. "))

if count > 0: # Check to avoid division by zero
average = sum / count
print("The average of the numbers is: ", average)
else:
print("No valid numbers were entered.")
```

In this corrected version:

1. A `count` variable is introduced to keep track of how many valid numbers were entered.
2. The average is computed as `sum / count`, ensuring that you're dividing by the number of inputs rather than the last input value.

The outcome of -135.0 in your original version can be referred to as a **logical error** or **semantic error** since the code syntactically runs without error but does not produce the intended outcome.
There are no human answers yet. A form for humans to post answers is coming very soon!

Related Questions