同事python开发人员。我有一项任务,我似乎无法破解,我的导师是MIA。我需要编写一个只使用while
循环,if
,elif
和else
语句的程序:
int(raw_input())
输入任意随机正整数这就是我到目前为止:
num = -1
counter = 1
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
counter += anyNumber
answer = counter + anyNumber
print answer
print "Good bye!"
您需要在代码末尾添加计算平均值。
为此,计算while循环运行的次数,并将该值除以该值。
此外,您的代码每次都会在答案中添加一个因为行 - answer = counter + anyNumber
,这不会产生正确的平均值。并且您缺少存储第一个输入数字,因为代码连续输入两个输入。这是一个固定版本:
num = -1
counter = 0
answer = 0
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
counter += 1
answer += anyNumber
anyNumber = int(raw_input("Enter another number: "))
if (counter==0): print answer #in case the first number entered was -1
else:
print answer/counter #print average
print "Good bye!"
尝试以下内容并询问您可能遇到的任何问题
counter = 0
total = 0
number = int(raw_input("Enter any number: "))
while number != -1:
counter += 1
total += number
number = int(raw_input("Enter another number: "))
if counter == 0:
counter = 1 # Prevent division by zero
print total / counter
我认为还有另一个问题:
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
变量anyNumber的值在循环之前和循环开始时更新,这意味着您将要输入的第一个值永远不会被考虑在平均值中。
一个不同的解决方案,使用更多功能,但更安全。
import numpy as np
numbers = []
while True:
# try and except to avoid errors when the input is not an integer.
# Replace int by float if you want to take into account float numbers
try:
user_input = int(input("Enter any number: "))
# Condition to get out of the while loop
if user_input == -1:
break
numbers.append(user_input)
print (np.mean(numbers))
except:
print ("Enter a number.")
你不需要保存总数,因为如果数字真的很大,你可以有溢出。仅使用avg应该足够了:
STOP_NUMBER = -1
new_number = int(raw_input("Enter any number: "))
count = 1
avg = 0
while new_number != STOP_NUMBER:
avg *= (count-1)/count
avg += new_number/count
new_number = int(raw_input("Enter any number: "))
count += 1
我建议跟随。
counter = input_sum = input_value = 0
while input_value != -1:
counter += 1
input_sum += input_value
input_value = int(raw_input("Enter any number: "))
try:
print(input_sum/counter)
except ZeroDivisionError:
print(0)
您可以避免使用两个raw_input
并使用while
循环内的所有内容。
还有另一种做法..
nums = []
while True:
num = int(raw_input("Enter a positive number or to quit enter -1: "))
if num == -1:
if len(nums) > 0:
print "Avg of {} is {}".format(nums,sum(nums)/len(nums))
break
elif num < -1:
continue
else:
nums.append(num)
虽然@ nj2237提供的解决方案也很完美,但这是我自己想要做的事情。
# Initialization
sum = 0
counter = 0
stop = False
# Process loop
while (not stop):
inputValue = int(raw_input("Enter a number: "))
if (inputValue == -1):
stop = True
else:
sum += inputValue
counter += 1 # counter++ doesn't work in python
# Output calculation and display
if (counter != 0):
mean = sum / counter
print("Mean value is " + str(mean))
print("kthxbye")