2015-02-01 12 views
1

내 CS 과정 중 하나의 과제를 준비 중입니다. 나는이 사실을 알아 냈다.하지만 while 루프 내에서 값을 반환하는 방법을 모른다.while 루프 내에서 값을 반환하는 방법

내가 겪고있는 문제는 t == 0이 될 때까지 while 루프를 통해 몫을 추가해야한다는 것입니다. 나는 분수를 추가 할 때까지 모든 것이 올바르게 작동합니다. 모두 함께 추가됩니다. 같은 두 숫자. 내가해야 할 일은 "나누기"가 루프를 통해 이전 용어와 같은지 기억하고 현재 루프가 계산하는 것에 그것을 더하는 것입니다.

나는 그것이 어떤 의미와도 같았 으면 좋겠다. Here is a link to the question for those of you who now have a headache after reading my question

# FORMULA IS AS FOLLOWS 
# 1 + x + (x^t)/(t!) until t == 1 

t = int(input("Enter a non negative integer for t: ")) 
x = float(input("Enter a real number for x: ")) 
fact = 1 
finalProduct = 1 
counter = 1 
while counter <= t : 
    counter = counter + 1 
    fact = fact * counter 

    print("counter:",counter) 
    print("fact:",fact) 


    xPwr = (x**counter) 

    division = (xPwr/fact) 
    print("Division: ",division)   
    addition = (division + division)#HERE IS MY PROBLEM 
    print("Sum:", addition) 

finalProduct = (1 + x + addition) 

print("finalProduct",finalProduct) 

답변

2

이 강사에 의해 주어진 문제 설명에 매우 밀접하게 다음과 같습니다

여기
Enter a real number for x: 2.0 
Enter a non negative integer for t: 3 
6.333333333333333 
+0

와우 나는 이것을 몇 시간 동안 알아 내려고 노력했다는 것을 믿을 수 없어 그게 전부였다. 정말 고마워. – HawkeyeNate

0

옆 루프에 변수를 전달하는 Recursive Functions를 사용해야합니다.

def factorial(n): 
    if n == 1: 
     return 1 
    else: 
     return n * factorial(n-1) 

다음 루프에는 "n-1"값이 전달됩니다.

+0

이 문제에 대한 도움뿐 아니라 훌륭한 사이트에 감사드립니다. – HawkeyeNate

+0

@HawkeyeNate 감사합니다! 받아 들일 수있는 답을 표시 할 수 있습니까? – mertyildiran

+1

어 ... 재귀에 적합한 문제가있는 동안, 이것은 그들 중 하나가 아닙니다! 반복적 인 솔루션은 더 빨라지고 메모리를 덜 사용합니다. –

-1

당신은 다시 로컬 Y 변수에 코어의 반환 값을 할당 할, 그것은 참조에 의해 전달 아니에요 :

Y = 코어 (x)는 또한 당신이에 가기 전에 y로 설정해야합니다 고리. 함수의 지역 변수는 다른 함수에서 사용할 수 없습니다.

결과, 전혀 코어 (x)는 Y를 통과 할 필요가 없습니다 :

def core(x): 
    y = input("choose a number: ") 
    if y == x: 
     print("You gussed the right number!") 
     return y 
    elif y > x: 
     print("The number is lower, try again") 
     return y 
    else: 
     print("The number is higher, try again") 
     return y 
and the loop becomes: 

y = None 
while (x != y) and (i < t): 
    y = core(x) 
    i += 1 

그것은 당신이 시작하는 main() 함수에서 y를별로 문제 설정하는 일 with, 사용자가 추측을하기 전에는 결코 x와 같지 않을 것입니다.

+0

도대체이게 뭐야? – HawkeyeNate

1

이 약간 확장 된 버전입니다 :

여기
x = float(input("Enter a real number for x: ")) 
t = int(input("Enter a non negative integer for t: ")) 
counter = 1 
series = 1 
num = 1 
denom = 1 
while counter <= t : 
    num = num * x 
    denom = denom * counter 
    series = series + num/denom 
    counter = counter + 1 
print(series) 

은 예입니다.

먼저 주어진 시리즈는 e ** x의 근사치임을 알아야합니다. 용어가 많을수록 최종 결과가 정확합니다. 의 그를 알아 보자 :

import math 

def approx_ex(x, max_t): 
    """ 
    Maclaurin series expansion for e**x 
    """ 
    num = 1  # == x**0 
    denom = 1  # == 0! 
    total = 1.0 # term_0 == (x**0)/0! 

    for t in range(1, max_t + 1): 
     # modify numerator and denominator to find next term 
     num *= x  # x**(t-1) * x == x**t 
     denom *= t  #  (t-1)! * t == t! 
     # keep a running total  
     total += num/denom 

    return total 

def main(): 
    x = float(input("Input a real number: ")) 

    actual = math.e ** x 
    print("\nApproximation of e ** {} == {}\n".format(x, actual)) 

    for terms in range(1, 16): 
     approx = approx_ex(x, terms) 
     error = approx - actual 
     print("{:>2d}: {:16.12f} ({:16.12f})".format(terms, approx, error)) 

if __name__ == "__main__": 
    main() 

이 결과가 더 용어가 함께 합산으로 더 나은 얻는 방법을 매우 명확하게 보여줍니다

Input a real number: 3.205 

Approximation of e ** 3.205 == 24.655500016456244 

1: 4.205000000000 (-20.450500016456) 
2: 9.341012500000 (-15.314487516456) 
3: 14.827985854167 (-9.827514162290) 
4: 19.224423254193 (-5.431076762264) 
5: 22.042539627609 (-2.612960388847) 
6: 23.547883457076 (-1.107616559380) 
7: 24.237115881853 (-0.418384134603) 
8: 24.513239622030 (-0.142260394426) 
9: 24.611570353948 (-0.043929662508) 
10: 24.643085353528 (-0.012414662928) 
11: 24.652267678406 (-0.003232338051) 
12: 24.654720124342 (-0.000779892115) 
13: 24.655324746590 (-0.000175269866) 
14: 24.655463161897 (-0.000036854559) 
15: 24.655492736635 (-0.000007279822) 

처럼 실행됩니다.

관련 문제