在python中显示输入提示

2024-05-26 21:51:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我在macos上使用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()

现在空闲将永久显示:

This program finds the real solution to a quadratic

Please enter the coefficients (a, b, c):

当我输入3个数字(例如:1,2,3)时,IDLE什么也不做。当我点击进入空闲崩溃(没有崩溃报告)。在

我退出并重新启动,但IDLE现在永久显示上述内容,不会响应其他文件。在


Tags: 文件thetomainmaththisprogramreal
3条回答

math模块不支持复数。如果将import math替换为import cmath,将{}替换为{},那么脚本的工作方式应该很有魅力。在

编辑:我刚读到“这个程序找到二次曲线的真正解”。考虑到你只想要真正的根,你应该像凯文所指出的那样,检查是否存在负面歧视。在

方程X^2+2x+3=0没有实际解。当你试图取b * b-4 * a * c的平方根时,你会得到一个ValueError,它是负数。你应该设法处理这个错误案例。例如,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()

或者您可以提前检测到判别式为负:

^{pr2}$

结果:

This program finds the real solution to a quadratic

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

我认为你的计划失败的原因是:

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

print num

结果是-8。在

通常平方根内不能有负数。在

就像我上面的人说的,导入cmath应该行得通。在

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

^{pr2}$

=2.82842712475j

相关问题 更多 >

    热门问题