简体   繁体   English

我如何在while循环中返回值

[英]How do I return a value within a while loop

I'm working on an assignment for one of my CS courses. 我正在为我的其中一门CS课程分配作业。 I've gotten this thing just about figured out, but I don't know how to return a value within my while loop. 我已经弄清楚了这件事,但是我不知道如何在我的while循环中返回值。

The problem I'm having is I need to add the quotient each time through the while loop until t == 0. I have everything working correct until I get to the addition of the division, all it is adding together the same two number. 我遇到的问题是,我每次都要通过while循环将商相加,直到t ==0。在使除法相加之前,所有工作都是正确的,所有的都将相同的两个数相加。 What I need it to do is remember what "division" was equal to the previous term through the loop then add it to what the current loop calculates. 我需要做的是记住整个循环中“除法”等于前一项,然后将其添加到当前循环的计算中。

I hope that made any semblance of sense. 我希望这看起来很合理。 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)

This follows very closely to the problem description given by your instructor: 这与您的老师给出的问题描述非常接近:

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)

Here is an example: 这是一个例子:

Enter a real number for x: 2.0
Enter a non negative integer for t: 3
6.333333333333333

Here is a slightly extended version. 这是一个稍微扩展的版本。

First, you should realize that the given series is an approximation of e ** x ; 首先,您应该意识到给定的级数是e ** x的近似值; the more terms are included, the more accurate the final result. 包含的术语越多,最终结果越准确。 Let's explore that: 让我们探索一下:

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()

This runs like 这就像

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)

which very clearly shows how the result gets better and better as more terms are summed together. 这非常清楚地表明,将更多的术语加在一起,结果会越来越好。

You should use Recursive Functions for passing a variable to next loop. 您应该使用递归函数将变量传递到下一个循环。

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

It is passing "n-1" value to next loop. 它将“ n-1”值传递给下一个循环。

You want to assign the return value of core back to the local y variable, it's not passed by reference: 您想将core的返回值分配回本地y变量,它不会通过引用传递:

y = core(x) You'll also need to set y before you go into the loop. y = core(x)在进入循环之前,您还需要设置y。 Local variables in functions are not available in other functions. 函数中的局部变量在其他函数中不可用。

As a result, you don't need to pass y to core(x) at all: 结果,您根本不需要将y传递给core(x):

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

It doesn't much matter what you set y to in the main() function to start with, as long as it'll never be equal to x before the user has made a guess. 最初在main()函数中将y设置为什么都无所谓,只要在用户做出猜测之前永远不等于x。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM