2013-08-22 104 views
2

我在Mac OS上使用Python的IDLE。我寫了一個.py文件如下:在python中顯示輸入提示

import math 
def main(): 
    print "This program finds the real solution to a quadratic" 
    print 

    a, b, c = input("Please enter the coefficients (a, b, c): ") 

    discRoot = math.sqrt(b * b-4 * a * c) 
    root1 = (-b + discRoot)/(2 * a) 
    root2 = (-b - discRoot)/(2 * a) 

    print 
    print "The solutions are: ", root1, root2 

main() 

IDLE現在永久顯示:

該程序發現真正解決二次

請輸入係數(A,B, c):

當我輸入3個數字(例如:1,2,3)IDLE什麼都不做。當我打進輸入IDLE崩潰(沒有崩潰報告)。

我退出並重新啓動,但IDLE現在正在永久顯示上述內容,並且不會響應其他文件。

+0

使用的終端。 – enginefree

+0

一個問題是你沒有在'math.sqrt'中看到'1,2,3'輸入引發的異常。 – alecxe

+0

在你的例子中,不應該b * b大於4ac? –

回答

1

math模塊不支持複數。如果您用import cmathmath.sqrt替換import mathcmath.sqrt,您的腳本應該像魅力一樣工作。

編輯:我只是讀「這個程序找到了一個二次方的真正解決方案」。考慮到你只想要真正的根源,你應該檢查凱文指出的否定判別式。

2

方程X^2 + 2x + 3 = 0沒有真正的解決方案。當試圖取b * b-4 * a * c的平方根時,您會得到一個ValueError,這是負值。你應該以某種方式處理這個錯誤情況。例如,一試/除外:

import math 
def main(): 
    print "This program finds the real solution to a quadratic" 
    print 

    a, b, c = input("Please enter the coefficients (a, b, c): ") 

    try: 
     discRoot = math.sqrt(b * b-4 * a * c) 
    except ValueError: 
     print "there is no real solution." 
     return 
    root1 = (-b + discRoot)/(2 * a) 
    root2 = (-b - discRoot)/(2 * a) 

    print 
    print "The solutions are: ", root1, root2 

main() 

或者你可以檢測判別爲負的時間提前:

import math 
def main(): 
    print "This program finds the real solution to a quadratic" 
    print 

    a, b, c = input("Please enter the coefficients (a, b, c): ") 

    discriminant = b * b-4 * a * c 
    if discriminant < 0: 
     print "there is no real solution." 
     return 
    discRoot = math.sqrt(discriminant) 
    root1 = (-b + discRoot)/(2 * a) 
    root2 = (-b - discRoot)/(2 * a) 

    print 
    print "The solutions are: ", root1, root2 

main() 

結果:

This program finds the real solution to a quadratic 

Please enter the coefficients (a, b, c): 1,2,3 
there is no real solution. 
1

的原因,我看到了你的計劃失敗是這樣的:

a, b, c = 1, 2, 3 
num = b * b - 4 * a * c 

print num 

它出來爲-8。

平方根內通常不能有負數。

就像我上面的人說的那樣,import cmath應該可以工作。

http://mail.python.org/pipermail/tutor/2005-July/039461.html

import cmath 

a, b, c = 1, 2, 3 

num = cmath.sqrt(b * b - 4 * a * c) 
print num 

= 2.82842712475j