0

好的,所以我制作了一个求解 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)
4

1 回答 1

5

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

if abs(ifstuffleft - ifstuffright) < tolerance:

tolerance你愿意接受的错误在哪里

于 2012-12-02T19:43:04.297 回答