You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python无try-except判断输入为整数或浮点数:实现二次方程程序

不使用try/except实现整数/浮点数验证与二次方程求解

可以实现,下面分两部分给出具体方案:

一、手动实现输入验证函数

核心思路是直接解析输入的字符串,检查其是否符合整数或浮点数的格式规则(支持正负号):

def is_number(s):
    # 处理空字符串
    if not s:
        return False
    # 处理正负号
    start = 0
    if s[0] in '+-':
        start = 1
        # 单独的正负号无效
        if len(s) == 1:
            return False
    num_part = s[start:]
    # 统计小数点数量
    dot_count = num_part.count('.')
    if dot_count > 1:
        return False
    # 分割整数和小数部分
    if dot_count == 1:
        left, right = num_part.split('.', 1)
        # 小数点前后不能同时为空(比如单独的"."无效)
        if not left and not right:
            return False
        # 检查左边是否全为数字(允许为空,比如".5")
        if left and not left.isdigit():
            return False
        # 检查右边是否全为数字(允许为空,比如"5.")
        if right and not right.isdigit():
            return False
    else:
        # 无小数点,检查是否全为数字
        if not num_part.isdigit():
            return False
    return True

这个函数能识别以下合法输入:

  • 整数:123、-456、+789
  • 浮点数:12.3、-.45、67.、+8.90

同时排除非法输入:abc、12a3、1.2.3、+、-.等。

二、完整的二次方程求解程序

结合上面的验证函数,实现“不可破”的求解程序,确保输入有效后再计算:

def is_number(s):
    if not s:
        return False
    start = 0
    if s[0] in '+-':
        start = 1
        if len(s) == 1:
            return False
    num_part = s[start:]
    dot_count = num_part.count('.')
    if dot_count > 1:
        return False
    if dot_count == 1:
        left, right = num_part.split('.', 1)
        if not left and not right:
            return False
        if left and not left.isdigit():
            return False
        if right and not right.isdigit():
            return False
    else:
        if not num_part.isdigit():
            return False
    return True

def get_valid_input(prompt):
    while True:
        user_input = input(prompt).strip()
        if is_number(user_input):
            # 转换为float(兼容整数和浮点数)
            return float(user_input)
        print("输入无效,请输入整数或浮点数!")

def solve_quadratic():
    print("求解二次方程 ax² + bx + c = 0")
    a = get_valid_input("请输入a的值(不能为0):")
    while a == 0:
        print("a不能为0,否则不是二次方程!")
        a = get_valid_input("请重新输入a的值:")
    b = get_valid_input("请输入b的值:")
    c = get_valid_input("请输入c的值:")
    
    # 计算判别式
    discriminant = b**2 - 4 * a * c
    a_double = 2 * a
    
    if discriminant > 0:
        sqrt_d = discriminant ** 0.5
        root1 = (-b + sqrt_d) / a_double
        root2 = (-b - sqrt_d) / a_double
        print(f"方程有两个不同的实根:x1 = {root1:.2f}, x2 = {root2:.2f}")
    elif discriminant == 0:
        root = -b / a_double
        print(f"方程有一个重根:x = {root:.2f}")
    else:
        # 处理复数根,手动构造虚部表示
        abs_d = -discriminant
        sqrt_abs_d = abs_d ** 0.5
        real_part = -b / a_double
        imag_part = sqrt_abs_d / a_double
        print(f"方程有两个共轭复根:")
        print(f"x1 = {real_part:.2f} + {imag_part:.2f}i")
        print(f"x2 = {real_part:.2f} - {imag_part:.2f}i")

# 运行程序
solve_quadratic()

说明:

  1. get_valid_input函数循环获取输入,直到用户输入合法的数字
  2. 额外检查了a不能为0的情况(因为二次方程要求a≠0)
  3. 判别式小于0时,手动处理复数根的输出格式,无需导入任何库
  4. 所有计算均使用Python内置的算术运算符,符合“不使用导入库”的要求

内容的提问来源于stack exchange,提问作者BasedGod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 03:23:36