2

Mac OS で IDLE for Python を使用しています。.py ファイルに次のように記述しました。

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 は何もしません。Enter キーを押すと、IDLE がクラッシュします (クラッシュ レポートはありません)。

終了して再起動しましたが、IDLE は上記を永続的に表示し、他のファイルに応答しません。

4

3 に答える 3

2

ValueError方程式 X^2 + 2x + 3 = 0 には真の解はありませんb * b-4 * a * c。このエラー ケースを何らかの方法で処理する必要があります。たとえば、try/except:

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.
于 2013-08-22T17:51:06.000 に答える