gpt4 book ai didi

c++ - 做了一个库存程序,不知道如何在 'for' 循环中添加总计

转载 作者:行者123 更新时间:2023-11-30 03:35:59 26 4
gpt4 key购买 nike

我在我的代码中遇到问题,不知道如何添加单独的成本,以获得 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;

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com