Komeyl
Komeyl

Reputation: 13

Take a few numbers and give the average of the numbers

I want to get some numbers from the user so that this continues until the user presses the number -1. After hitting the number -1, the program will give him the average of the previous numbers. My code works but miscalculates the mean. what is the problem?

  sum = 0
  count = 0 
  x = []
  while x != -1 :
      x = int(input())
      sum += x
      count += 1

  averagex = sum / count 
  print(averagex)


   

Upvotes: 1

Views: 60

Answers (2)

azro
azro

Reputation: 54148

Fow now your verification of the input is done at while x != -1 which is executed after the input, the sum and the count part, so the -1 will be part of the result, thing that you don't want.

A simple if will fix that :

total, count, x = 0, 0, 0
while True:
    x = int(input("Enter a value: "))
    if x == -1:
        break
    total += x
    count += 1

Avoid using builtin function names, such as sum, for variable naming

Upvotes: 0

BTables
BTables

Reputation: 4833

Your loop terminates after the user enters -1. This means on the last iteration 1 will be subtracted from the total and count will be one higher than it should be. Try this:

  while True:
      x = int(input())
      if x == -1:
          break
      sum += x
      count += 1

Upvotes: 1

Related Questions