制作了一个库存程序,不知道如何在'for'循环中添加总计

时间:2016-12-02 03:47:20

标签: c++

我在代码中遇到问题,不知道如何添加个人费用,以获得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;
}

2 个答案:

答案 0 :(得分:1)

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

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

幸运的是,totalCost实际上在此时保持为零,因此代码将在没有此更改的情况下运行。

接下来,您要总结totalCost

   cout << "Current bill is " << cost << endl;
   totalCost += cost;
}

此外,您的totalCost += cost位于for循环之外,因此我将其移至内部。

最后,您需要打印totalCost

cout << "Your total bill is  Rs. " << totalCost << endl;

可能仍有问题,包括我暗示未来08 compile error

答案 1 :(得分:1)

你的代码看起来很不错,你需要在for循环结束时反转总和,你正在做:

cost+=totalCost;

但必须是:

totalCost+=cost;

并且不要忘记在getData方法中返回 totalCost :)