Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

I want to multiply two different structures in c language

I'm a student of BS Computer Science. I am working on inventory system which is a first project to me from my uni. But I am facing one problem while working on ending inventory. I want to add opening and purchase and then subtract sell from it.. But I am unable to do so. Please help me to solve this issue.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Consider the structure:

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

Now, we go through the store and get inventory of stuff and we then go through the warehouse and get another inventory. We then want a total inventory (data and data1). We can do the following, including printouts:

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
",
           data[i].quant, data1[i].quant, total)
}

So, total is the total from the two structures (I am assuming that the ith element of each data array are for the same items - you should probably check that before you do the printout). The printout will occur on one line (because there is no at the end of the first printf).

Now, if you want to manipulate elements of the structure, that is also simple. Consider:

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;

This example shows manipulating elements of a structure. You can also use a function to do the same thing and pass a pointer to the structure. This is actually more flexible since it doesn't care or know about how many different inventory items you have:

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;
}

And there you go - a way to access structure elements across multiple instances of the structure and a way to access and manipulate elements within a structure.

Good Luck


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...