我在我的代码中遇到问题,不知道如何增加个人成本,获取totalCost,请帮助我解决这个问题。
我已经应用for循环来获取成本并确定价格,现在我可以根据需要获取单个成本,但是totalCost中有问题。

#include <iostream>
using namespace std;

class Inventory
{
private:
    int itemNumber;
    int quantity;
    double cost;
    double totalCost;
public:
    Inventory()
    {
        itemNumber = 0;
        quantity = 0;
        cost = 0;
        totalCost = 0;
    }
    void data();
    double getdata();
    void display();
};

void Inventory :: data()
{
    cout << "Welcome to Waqar Milk Shop, we have varieties for your breakfast\n"
    << "Items available at our store are:\n"
    << "01. Eggs(Rs10/one)   02. Bread(Rs70/one)   03. Butter(Rs60/one)   04. Milk(Rs80/kg)"
    << "   05. Yogurt(Rs120/kg)\n"
    << "Please select anything you want, only press numeric code, Press 06 to exit\n\n";
}
double Inventory :: getdata()
{
    do
    {
        int i;
        cout << "how many items do you want to purchase?\n";
        cin >> i;
        for (int j=totalCost; j< i;j++)
        {
            cout << "Item:  ";  cin >> itemNumber;
            cout << "Quantity:  "; cin >> quantity;
            switch (itemNumber)
            {
                case 01: cost= 10*quantity; break;
                case 02: cost= 70*quantity;  break;
                case 03: cost= 60*quantity;  break;
                case 04: cost= 80*quantity;  break;
                case 05: cost= 120*quantity; break;
                default: cout << "Sorry this item does not exist";
            }
            cout << "Current bill is " << cost << endl;
        }   cost+=totalCost;
    } while (itemNumber==06);
}

void Inventory :: display()
{
    cout << "Your total bill is  Rs. " << cost << endl;
}

int main()
{
    Inventory a;
    a.data();
    a.getdata();
    a.display();
    return 0;
}

最佳答案

评论字段中没有足够的空间,但是您需要首先从零到元素数循环:

for (int j = 0; j < i; j++)

幸运的是,totalCost当时实际上为零,因此代码无需更改即可运行。

接下来,您要总结totalCost:
   cout << "Current bill is " << cost << endl;
   totalCost += cost;
}

另外,您的totalCost += costfor循环之外,所以我将其移到了里面。

最后,您需要打印totalCost:
cout << "Your total bill is  Rs. " << totalCost << endl;

可能仍然存在问题,包括我暗示将来的 08 compile error

关于c++ - 做了一个库存计划,不知道如何在 'for'循环中添加总计,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40924448/

10-13 05:07