c - 我想用c语言将两个不同的结构相乘

标签 c

我是计算机科学学士学位的学生。我正在研究库存系统,这是我在大学的第一个项目。但我在处理库存时面临一个问题。我想添加开仓和买入,然后从中减去卖出。但我无法这样做。请帮我解决这个问题。

最佳答案

考虑结构:

struct inventory
{
    char id[10];
    char item[20];
    int  quant;
    int cost;
} data[20], data1[20];

现在,我们遍历商店并获取商品库存,然后遍历仓库并获取另一个库存。然后我们需要一个总库存(数据和数据1)。我们可以执行以下操作,包括打印输出:

int total;
for (i = 0; i < 20; i++)
{
    total = data[i].quant + data1[i].quant;
    printf("Item %s, ID %s: ", data[i].item, data[i].id);
    printf("Store: %5d  Warehouse: %5d  Total: %6d\n",
           data[i].quant, data1[i].quant, total)
}

因此,total 是两个结构的总计(我假设每个数据数组的第 i 个元素用于相同的项目 - 您可能应该在打印输出之前检查一下)。打印输出将发生在一行上(因为第一个 printf 的末尾没有\n)。

现在,如果您想操作结构的元素,那也很简单。考虑:

struct items
{
    int opening, purchase, sell;
} element;

int remaining;
// Calculate the remaining items:
remaining = element.opening + element.purchase - element.sell;

// ... <other processing>
// Do printouts, etc. with information
// ...

// Now update structure for the next cycle.
element.opening  = remaining;
element.purchase = 0;
element.sell     = 0;

此示例显示了对结构元素的操作。您还可以使用函数来执行相同的操作并传递指向结构的指针。这实际上更灵活,因为它不关心或不知道您有多少不同的库存项目:

int getRemaining(struct items *item)
{
    int remaining;
    remaining = item->open + item->purchase - item->sell;
    item->open = remaining;
    item->purchase = 0;
    item->sell     = 0;
    return remaining;
}

这就是 - 一种跨结构的多个实例访问结构元素的方法以及一种访问和操作结构内的元素的方法。

祝你好运

关于c - 我想用c语言将两个不同的结构相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30829923/

相关文章:

c - 使用指针作为函数参数的字符串复制。

c - 错误无法将参数 'int**' 转换为 'int*' 到 '1'

c - 用 C 语言复制 Spinrite 动画效果

c - 调用malloc()和free()时寄存器/缓存和主存之间是否有数据传输

c - 无法使用 ESP8266 上传 HTML 页面

c - 如何在c程序中获取每个整数秒

c - 父进程在无限循环中杀死子进程

c - 虚拟到内核逻辑地址

c - 如何在GEdit中获得GTK语法高亮?

c++ - 将 LARGE_INTEGER.QuadPart 作为 size_t 的输出参数传递是否安全?