海鸥示例代码
HarmonyOS 5
数学类上架项目解析2-一元二次方程求解算法
在开发鸿蒙数学计算应用时,需要实现一元二次方程 ax² + bx + c = 0 的求解功能。要求:
1. 能够根据判别式 Δ = b² - 4ac 判断根的类型
2. 支持两个不等实根、两个相等实根、两个共轭复根三种情况
3. 结果需要支持小数、分数等多种显示格式
如何用ArkTS实现一个完整的一元二次方程求解器?

一元二次方程求解是基于求根公式: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. 复数根需要分别计算实部和虚部,格式化为字符串显示
- 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
- 如您发布的内容为转载内容,请注明内容来源。
我要提问题
HarmonyOS 应用有哪些上架方式 (API12)
HarmonyOS 版本上架咨询 (API12+)
HarmonyOS 二次贝塞尔曲线函数结束点计算。 (API12+)
HarmonyOS 分布式文件系统在 ArkTS 项目中的应用?(API12+)
如何实现数学公式渲染
HarmonyOS C调用ArkTS的异步方法问题 (API12+)
HarmonyOS 对于复杂的逻辑代码,ArkTS提供了哪些性能调试工具快速定位问题? (API12+)
HarmonyOS ArkTS是否支持枚举类中添加方法(API12+)




































苏公安网备 32011402010933号