文档开发者中心
我的
|

示例代码

HarmonyOS 5

数学类上架项目解析2-一元二次方程求解算法

在开发鸿蒙数学计算应用时,需要实现一元二次方程 ax² + bx + c = 0 的求解功能。要求:

1. 能够根据判别式 Δ = b² - 4ac 判断根的类型

2. 支持两个不等实根、两个相等实根、两个共轭复根三种情况

3. 结果需要支持小数、分数等多种显示格式

如何用ArkTS实现一个完整的一元二次方程求解器?

点赞
收藏
回复
1
分享
举报
浏览115 发布于2025-12-24 16:34湖北
全部评论
最多点赞
最新发布
最早发布

一元二次方程求解是基于求根公式:x = (-b ± √Δ) / 2a,其中判别式 Δ = b² - 4ac 决定了根的类型:

- Δ > 0:两个不等实根

- Δ = 0:两个相等实根(重根)

- Δ < 0:两个共轭复根

解决方案分为三个部分:数据模型定义、求解计算、UI展示。

1. 定义求解结果数据模型

收起
自动换行
深色代码主题
复制
// 根的类型枚举

enum RootType {

  TWO_REAL = 'two-real',      // 两个不等实根

  ONE_REAL = 'one-real',      // 两个相等实根

  COMPLEX = 'complex'         // 两个共轭复根

}
收起
自动换行
深色代码主题
复制
// 求解结果接口

interface QuadraticResult {

  type: RootType

  delta: number

  x1: string

  x2?: string

}

2. 核心求解函数

/

  求解一元二次方程 ax² + bx + c = 0

  @param a x²的系数(不能为0)

  @param b x的系数

  @param c 常数项

  @returns 求解结果

 /

收起
自动换行
深色代码主题
复制
function solveQuadratic(a: number, b: number, c: number): QuadraticResult {

  // 输入验证

  if (Number.isNaN(a) || Number.isNaN(b) || Number.isNaN(c)) {

    throw new Error('请输入有效数字')

  }



  if (a === 0) {

    throw new Error('a不能为0,这不是一元二次方程')

  }



  // 计算判别式

  const delta: number = b  b - 4  a  c



  if (delta > 0) {

    // 两个不等实根

    const x1: number = (-b + Math.sqrt(delta)) / (2  a)

    const x2: number = (-b - Math.sqrt(delta)) / (2  a)

    return {

      type: RootType.TWO_REAL,

      delta: delta,

      x1: x1.toFixed(4),

      x2: x2.toFixed(4)

    }

  } else if (delta === 0) {

    // 两个相等实根(重根)

    const x: number = -b / (2  a)

    return {

      type: RootType.ONE_REAL,

      delta: delta,

      x1: x.toFixed(4)

    }

  } else {

    // 两个共轭复根

    const realPart: number = -b / (2  a)

    const imagPart: number = Math.sqrt(-delta) / (2  a)

    return {

      type: RootType.COMPLEX,

      delta: delta,

      x1: ${realPart.toFixed(4)} + ${imagPart.toFixed(4)}i,

      x2: ${realPart.toFixed(4)} - ${imagPart.toFixed(4)}i

    }

  }

}

3. 完整UI组件实现

收起
自动换行
深色代码主题
复制
@Entry

@Component

struct QuadraticSolver {

  @State coeffA: string = ''

  @State coeffB: string = ''

  @State coeffC: string = ''

  @State result: QuadraticResult | null = null

  @State errorMsg: string = ''



  build() {

    Column() {

      Text('一元二次方程求解器')

        .fontSize(24)

        .fontWeight(FontWeight.Bold)

        .margin({ bottom: 20 })



      Text('ax² + bx + c = 0')

        .fontSize(18)

        .margin({ bottom: 20 })



      // 输入区域

      Row() {

        TextInput({ placeholder: 'a' })

          .width(80)

          .onChange((value: string) => { this.coeffA = value })

        Text('x² +').margin({ left: 8, right: 8 })

        TextInput({ placeholder: 'b' })

          .width(80)

          .onChange((value: string) => { this.coeffB = value })

        Text('x +').margin({ left: 8, right: 8 })

        TextInput({ placeholder: 'c' })

          .width(80)

          .onChange((value: string) => { this.coeffC = value })

        Text('= 0').margin({ left: 8 })

      }

      .margin({ bottom: 20 })



      // 求解按钮

      Button('求解')

        .onClick(() => this.handleSolve())

        .width(200)

        .margin({ bottom: 20 })



      // 结果显示

      if (this.errorMsg) {

        Text(this.errorMsg)

          .fontColor(Color.Red)

          .margin({ top: 10 })

      }



      if (this.result) {

        Column() {

          Text(判别式 Δ = ${this.result.delta.toFixed(4)})

            .margin({ bottom: 10 })

         

          if (this.result.type === RootType.TWO_REAL) {

            Text('两个不等实根:')

            Text(x₁ = ${this.result.x1})

            Text(x₂ = ${this.result.x2})

          } else if (this.result.type === RootType.ONE_REAL) {

            Text('两个相等实根(重根):')

            Text(x = ${this.result.x1})

          } else {

            Text('两个共轭复根:')

            Text(x₁ = ${this.result.x1})

            Text(x₂ = ${this.result.x2})

          }

        }

        .alignItems(HorizontalAlign.Start)

        .padding(16)

        .backgroundColor('#f5f5f5')

        .borderRadius(8)

      }

    }

    .width('100%')

    .height('100%')

    .padding(20)

  }



  handleSolve(): void {

    this.errorMsg = ''

    this.result = null



    const a: number = parseFloat(this.coeffA)

    const b: number = parseFloat(this.coeffB)

    const c: number = parseFloat(this.coeffC)



    try {

      this.result = solveQuadratic(a, b, c)

    } catch (error) {

      this.errorMsg = (error as Error).message

    }

  }

}

4. 使用示例

// 示例1:两个不等实根 x² - 5x + 6 = 0

const result1 = solveQuadratic(1, -5, 6)

// { type: 'two-real', delta: 1, x1: '3.0000', x2: '2.0000' }

// 示例2:两个相等实根 x² - 4x + 4 = 0

const result2 = solveQuadratic(1, -4, 4)

// { type: 'one-real', delta: 0, x1: '2.0000' }

// 示例3:两个共轭复根 x² + 2x + 5 = 0

const result3 = solveQuadratic(1, 2, 5)

// { type: 'complex', delta: -16, x1: '-1.0000 + 2.0000i', x2: '-1.0000 - 2.0000i' }

总结

使用ArkTS实现一元二次方程求解的关键点:

1. 使用枚举类型RootType定义根的类型,代码更规范

2. 使用接口QuadraticResult定义返回结果结构,类型安全

3. 通过@State装饰器实现响应式数据绑定,输入变化自动更新UI

4. 判别式Δ是算法核心,决定了三种不同的计算分支

5. 复数根需要分别计算实部和虚部,格式化为字符串显示

6. 项目链接:https://gitee.com/solgull/math-fbox

展开全部
1楼回复于2025-12-25 07:03 来自湖北
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要提问题

了解社区公约,与您携手共创和谐专业的开发者社区。