我被困在为计算机科学课编写的C++程序上
I'm stuck on a C++ program that i'm writing for my computer science class
当我尝试运行此程序时,它将为我的getTotalCost()
函数输出0,我无法弄清楚为什么。
这是两个类文件:
shoppingcart.cpp
#include "ShoppingCart.h"
#include <iostream>
#include <string>
using namespace std;
ShoppingCart::ShoppingCart()
{
customerName = "None";
}
ShoppingCart::ShoppingCart(string name)
{
customerName = name;
}
string ShoppingCart::getCustomerName() const
{
return customerName;
}
void ShoppingCart::addItem(ItemToPurchase item)
{
cartItems.push_back(item);
}
void ShoppingCart::removeItem(string name)
{
for (int i = 0; i < cartItems.size(); i++)
{
if (cartItems.at(i).getName() == name)
{
cartItems.erase(cartItems.begin() + i);
}
else
{
cout << "Item not found in cart. Nothing removed." << endl;
}
}
}
void ShoppingCart::changeQuantity(string name, int quantity)
{
for (int i = 0; i < cartItems.size(); i++)
{
if (cartItems.at(i).getName() == name)
{
cartItems[i].setQuantity(quantity);
}
else
{
cout << "Item not found in cart. Nothing modified." << endl;
}
}
}
double ShoppingCart::getTotalCost()
{
double sum = 0.0;
for (int i = 0; i < cartItems.size(); i++)
{
sum += cartItems[i].getQuantity() * cartItems[i].getPrice();
}
return sum;
}
void ShoppingCart::printCart()
{
cout << customerName << "'s Shopping Cart" << endl;
for (int i = 0; i < cartItems.size(); i++)
{
cartItems.at(i).printItemCost();
}
cout << endl;
cout << "Total: $" << getTotalCost() << endl;
}
shoppingcart.h
#ifndef ShoppingCart_hpp
#define ShoppingCart_hpp
#include <string>
#include <vector>
#include "ItemToPurchase.h"
using namespace std;
class ShoppingCart
{
private:
string customerName;
vector<ItemToPurchase> cartItems;
public:
ShoppingCart();
ShoppingCart(string name);
string getCustomerName() const;
void addItem(ItemToPurchase);
void removeItem(string);
void changeQuantity(string, int);
double getTotalCost();
void printCart();
};
#endif
我的怀疑是,getTotalCost添加0值:
cartItems[i].getQuantity() * cartItems[i].getPrice();
如果两个因素之一为零,则整个总和保持0。
相关文章:
- cout 在我的程序上无法正常工作,有人可以帮助我吗?
- 视窗 10 :笔(手写笔)在 MFC 应用程序上不起作用
- c++程序上的奇怪编译错误
- 使用代码在 AWS 开发工具包C++控制台应用程序上设置凭证
- 在C++程序上同时运行的不同任务
- OutputDebugString在Windows通用应用程序上的位置?以及如何从OutputDebugString捕获
- 按下Arduino按钮后,如何在C#应用程序上执行操作
- Windows10 上的 VS Code + WSL 应用程序上的 CMake 扩展
- 为什么在此C++程序上添加负整数会导致正整数?
- 如何在没有第三方库的C 程序上显示图形
- 我被困在为计算机科学课编写的C++程序上
- 如何修复程序上的错误以衡量性能
- lambda回调中Android Cocos2D-X应用程序上的SEG故障
- 如何在Qt Android应用程序上禁用屏幕保护程序
- 如果我在 Xbox UWP 应用程序上收到激活错误并且错误消息中没有任何有用的内容,该怎么办
- 如何防止从浏览器查看图像,但允许在桌面应用程序上
- ShowCursor(FALSE) 不会在控制台应用程序上隐藏光标
- 在C 程序上嵌入Ruby源的错误
- 我在这个程序上遇到了麻烦.只有1个编译错误
- 在已经运行的C 控制台应用程序上实现QT GUI