2. 半加器原理

场景:演示半加器如何计算两个1位二进制数的和与进位。
核心逻辑:S = A XOR B, C = A AND B。

@Entry
@Component
struct HalfAdder {
  @State a: number = 0
  @State b: number = 0

  build() {
    Column({ space: 30 }) {
      Text('半加器 Half Adder').fontSize(24)

      Row({ space: 50 }) {
        // 输入A
        Button(`A: ${this.a}`).onClick(() => this.a = this.a === 0 ? 1 : 0)
        // 输入B
        Button(`B: ${this.b}`).onClick(() => this.b = this.b === 0 ? 1 : 0)
      }

      Divider().margin(10)

      // 逻辑运算部分可视化
      Row() {
        // XOR门计算和
        Column() {
          Text('XOR Gate').fontSize(12)
          Text(`Sum (S): ${this.a ^ this.b}`).fontSize(20).fontColor(Color.Blue)
        }.padding(10).borderWidth(1)

        Blank().width(20)

        // AND门计算进位
        Column() {
          Text('AND Gate').fontSize(12)
          Text(`Carry (C): ${this.a & this.b}`).fontSize(20).fontColor(Color.Red)
        }.padding(10).borderWidth(1)
      }

      Text(`结果: ${this.a & this.b}${this.a ^ this.b} (二进制)`).fontSize(18).margin({ top: 20 })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐