【问题标题】:My Python Equation Solver Can't Solve for Fractions我的 Python 方程求解器无法求解分数
【发布时间】:2012-12-02 19:40:10
【问题描述】:

好的,所以我制作了一个求解 x 的小型方程求解器。它适用于整数值,但每当我尝试求解分数时,它都会进入无限循环。这是我的代码:

print "Make the variable in your equation stand for x"
print
startingLimit=int(raw_input("What is the lowest estimate that your variable could possibly be?"))
print
wholeNumber=raw_input("Do you know if your variable will be a whole number or a fraction? Answer: yes/no")
if (wholeNumber== "yes"):
    print
    fraction= raw_input("Is it a decimal/fraction? Answer:yes/no")
    if (fraction=="yes"):
        print
        print "This program will only calculate up to the 2nd place to the right of the decimal"
        xfinder=float(0.01)
    else:
        xfinder=int(1)
else:
    xfinder=float(0.01)


leftEquation=raw_input("Enter your left side of the equation:")
print
rightEquation=raw_input("Enter the right side of the equation:")
print
amountSolutions=100

print

#solving

a=0
indivisualCount=0
count=0
x=float(startingLimit)
while (count!=amountSolutions):
    ifstuffleft=eval(leftEquation)
    ifstuffright=eval(rightEquation)
    if (ifstuffleft!=ifstuffright):
        x=float(x+xfinder)
        print x
    else:
        a=(a+1)
        count=count+1
        print "Solution",a,"=",x
        print
        x=float(x+xfinder)

【问题讨论】:

    标签: python loops integer equation


    【解决方案1】:

    if (ifstuffleft!=ifstuffright): 应该变成

    if abs(ifstuffleft - ifstuffright) < tolerance:

    tolerance 是你愿意接受的错误

    【讨论】:

    • 这强调了 OP 需要了解浮点值是如何存储在计算机上的。
    • @Jonathon Reinhart,不要生气,但这看起来不像是对 OP 的建设性回应。至少给他一个指向 python 手册部分的链接:docs.python.org/2/tutorial/floatingpoint。对于 user1624992,问题是如何在计算机内部处理浮点数,使相等测试成为几乎永远不会返回 True 的危险操作的表示,这就是为什么您的程序陷入无限循环
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 2016-07-24
    相关资源
    最近更新 更多