Issue
I've made this console application and it works...but only when you enter small numbers in the input like 1 in 'ifrom', 2 in 'step', and 3 in 'to'...but when I enter bigger numbers in 'to' for example 100 it just do nothing!!! It even doesn't give me any error! Thanks!
print("---Average2---"+"\n")
sum=0
average=0
counter=0
while True:
ifrom=int(input("From: "))
step=int(input("Step: "))
to=int(input("To: "))
while sum<=to:
sum=ifrom+step
counter+=1
if sum==to:
print("\n"+"The sum is: ",sum)
average=sum/counter
print("The average is: ",average,"\n")
sum=0
average=0
counter=0
break
Solution
There are two reasons of this behavior
- You're adding constantly
sum = ifrom + step
which is a constant value (in your example:1 + 2 = 3
). So in every loop iteration your sum will be3
and will never hit 100 - Even if you fix the first problem, your example
sum
variable is going to be1, 3, 5, ..., 99, 101, ...
. You're checking if thesum
is 100 and the program is doing nothing, because it will bever hit 100.
Possible solutions:
use range syntax (recommended - you can use this solution )
check if the variable reached 100 (instead of checking if it is equal 100) like below:
print("---Average2---"+"\n")
average=0
counter=0
tmp=0
while True:
ifrom=int(input("From: "))
step=int(input("Step: "))
to=int(input("To: "))
tmp = ifrom
sum = tmp
while tmp<=to:
tmp+=step
sum+=tmp
counter+=1
if tmp>=to:
if tmp>to:
sum-=tmp
print("\n"+"The sum is: ",sum)
average=sum/counter
print("The average is: ",average,"\n")
sum=0
average=0
counter=0
break
Answered By - Dawid Wijata
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.