c - 更新 Arduino 中的结构

标签 c

我在 Arduino 中有一个如下所示的结构,我想更新它

struct record
{
   int bookId;
   int qtyInStock;

};

typedef struct record Record;

Record aRec;
aRec.bookId = 100;
aRec.qtyInStock = 12;

aRec.bookId = 101;
aRec.qtyInStock = 10;

aRec.bookId = 102;
aRec.qtyInStock = 100;

如果 bookId 101 已售出,我该如何更新 qtyInStock?因此,bookId 101 的 qtyInStock 现在应该为 9。

谢谢

最佳答案

您可以使用记录类型的数组来存储多本书。已出售为您的内置功能,您可以尝试以下操作:

struct record
{
   int bookId;
   int qtyInStock;

};
typedef struct record Record;
void sold(int id, Record* records) {
  int i;
  for(i=0;i<3;i++) {
    if(records[i].bookId == id) {
      records[i].qtyInStock--;
    }
  }
}
void updateId(int id, int new_id, Record* records) {
  int i;
  for(i=0;i<3;i++) {
    if(records[i].bookId == id) {
        records[i].bookid = new_id;
    }
  }
}
void updateQty(int id, int new_qty, Record* records) {
  int i;
  for(i=0;i<3;i++) {
    if(records[i].bookId == id) {
        records[i].qtyInStock = new_qty;
    }
  }
}
void main() {
  Record records[3];
  records[0].bookId = 100;
  records[0].qtyInStock = 12;
  records[1].bookId = 101;
  records[1].qtyInStock = 10;
  records[2].bookId = 102;
  records[2].qtyInStock = 100;
  int i;
  sold(101, records);
  updateId(100, 99, records);
  updateQty(102, 15, records);
  for(i=0;i<3;i++) {
    printf("%d\n", records[i].bookId);
    printf("%d\n\n", records[i].qtyInStock);
  }
}

关于c - 更新 Arduino 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47279806/

相关文章:

c - 来自 fgets() 的段错误

c - 二元矩阵 vector 乘法的本质

c - 链表添加元素

c - 在 C 中将 uint8 拆分为 4 个单元 2,以便稍后获得单元 10

ctype.h isdigit 不适用于 argv

C - 如何为每个数组元素动态分配内存?

c++ - 如何知道用于构建 linux 的 gcc 版本?

c - 如何计算同时运行的所有子进程的总执行时间?

c - 在 C 中预填充标准输入

c - 为什么 BLAS dsyrk 比简单的 C 实现更精确?