
回复
基本的计算器,包含加减乘除功能。我们需要确保代码结构正确,特别是ArkTS的语法和组件使用。同时,简单应用的开发要做到界面简洁,操作直观,所以布局设计要合理。
@Entry
@Component
struct Calculator {
@State currentInput: string = '0' // 当前输入显示
@State firstNum: number = 0 // 第一个操作数
@State operator: string = '' // 当前运算符
@State isNewNum: boolean = true // 是否开始新输入
// 按钮点击处理
handleButtonClick(value: string) {
if (value >= '0' && value <= '9') {
if (this.isNewNum) {
this.currentInput = value
this.isNewNum = false
} else {
this.currentInput += value
}
} else if (value === 'C') {
this.resetCalculator()
} else if ('+-×÷'.includes(value)) {
this.firstNum = parseFloat(this.currentInput)
this.operator = value
this.isNewNum = true
} else if (value === '=') {
this.calculateResult()
}
}
// 执行计算
private calculateResult() {
const secondNum = parseFloat(this.currentInput)
let result = 0
switch (this.operator) {
case '+':
result = this.firstNum + secondNum
break
case '-':
result = this.firstNum - secondNum
break
case '×':
result = this.firstNum * secondNum
break
case '÷':
result = secondNum !== 0 ? this.firstNum / secondNum : NaN
break
}
this.currentInput = isNaN(result) ? '错误' : result.toString()
this.isNewNum = true
}
// 重置计算器
private resetCalculator() {
this.currentInput = '0'
this.firstNum = 0
this.operator = ''
this.isNewNum = true
}
build() {
Column({ space: 10 }) {
// 显示区域
Text(this.currentInput)
.fontSize(48)
.width('90%')
.textAlign(TextAlign.End)
.margin(20)
// 按钮布局
Grid() {
ForEach([
'7', '8', '9', '÷',
'4', '5', '6', '×',
'1', '2', '3', '-',
'C', '0', '=', '+'
], (item: string) => {
GridItem() {
Button(item)
.fontSize(32)
.width('90%')
.height(80)
.backgroundColor('#F0F0F0')
.onClick(() => this.handleButtonClick(item))
}
})
}
.columnsTemplate('1fr 1fr 1fr 1fr')
.rowsTemplate('1fr 1fr 1fr 1fr')
.height('60%')
.width('100%')
}
.width('100%')
.height('100%')
.padding(10)
}
}
基本运算:支持加(+)、减(-)、乘(×)、除(÷)四则运算
连续输入:可连续输入多位数字(如:123.45)
错误处理:除数为零时显示"错误"
清除功能:点击C键重置计算器
界面布局:4×4网格按钮布局,数字右对齐显示