【问题标题】:I'm stuck on a C++ program that i'm writing for my computer science class [closed]我被困在为我的计算机科学课编写的 C++ 程序上[关闭]
【发布时间】:2018-04-24 05:43:17
【问题描述】:

当我尝试运行这个程序时,它为我的 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 

【问题讨论】:

  • 附带说明,在头文件中使用using namespace std 通常不是一个好习惯(例如,在您的customerName 类成员的情况下:std: :string customerName)
  • 我个人认为这不是一个好主意,我不喜欢使用它,但我的教授让我们这样做。
  • 我看不出这段代码有什么问题。也许忘记添加一个项目?将数量或价格设置为零?也许您可以在changeQuantity 等中添加一个检查。
  • 我可以看到四个可能的原因:1)购物车是空的; 2)您的物品数量为零; 3) 您的商品价格为零; 4) 某些商品的价格或数量为负,它们加起来为零。我怀疑您要么 a) 将商品添加到与您正在检查的购物车不同的购物车中,要么 b) 将默认构造的商品添加到购物车中。

标签: c++ c++14


【解决方案1】:

我的怀疑是,getTotalCost 增加了 0 个值:

cartItems[i].getQuantity() * cartItems[i].getPrice();

如果两个因子之一为零,则总和保持为 0。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 2013-01-29
    • 2010-10-28
    • 2010-11-15
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多