【问题标题】:Need help implementing functions in GroceryItem class需要帮助在 GroceryItem 类中实现功能
【发布时间】:2016-07-06 13:29:20
【问题描述】:

您好,我在创建 GroceryItem 类和使用函数接受和设置用户输入时遇到了一些麻烦。

目前,当我运行 dataEntry 函数时,编译器会在接受来自第一个函数的输入之前转到下一个函数。

我创建了一个测试牛奶对象来测试我的代码,但它不允许我在进入下一个输入提示之前输入数据。

一旦我能找出类函数,我还将创建一个对象数组并为其输入值。

任何关于如何修复此类和函数的建议将不胜感激!

#include <iostream>

using namespace std;

class GroceryItem{
private: int stockNumber;
         double price = 0.0;
         int quantity;
         double totalValue;
         double setPrice();
         int setStockNum();
         int setQuantity();
         void setTotalValue();
public:
    void dataEntry();
    void displayValues();

};
int GroceryItem::setStockNum(){
    int stock = 0;
cout << "Enter the stock number for the grocery item: ";

do {
    cout << "Stock Number(1000-9999): ";
    cin >> stock;
} while (!(stock >= 1000 && stock <= 9999));

    stockNumber = stock;
    return stockNumber;
}
double GroceryItem::setPrice(){
    double x = 0.0;
    cout << "Enter the price of the item: ";
    while (!(x > 0))    {
        cout << "Please enter a positive number for price!";
        cin >> x;
    }
    price = x;
    return price;
}
int GroceryItem::setQuantity(){
    int x = 0;
    cout << "Enter the quantity in stock: ";
    while (!(x > 0)){
        cout << "Please enter a positive number for quantity!";
        cin >> x;
    }
    quantity = x;
    return quantity;
}
void GroceryItem::setTotalValue(){
    totalValue = (quantity * price);
}
void GroceryItem::dataEntry(){
    setStockNum();
    system("pause");
    setPrice();
    system("pause");
    setQuantity();
    system("pause");
    setTotalValue();
}
void GroceryItem::displayValues(){
    cout << "Stock number: " << stockNumber;
    cout << "\nItem price: " << price;
    cout << "\nQuantity on hand: " << quantity;
    cout << "\nTotal value of item: " << totalValue;
}


int main(){
    GroceryItem Milk;
    Milk.dataEntry();
    Milk.displayValues();
    system("pause");
    return 0;
}

【问题讨论】:

  • 你这是什么意思?这不是有效的代码行,所以不确定您的意思
  • 您应该使用构造函数初始化price 成员。
  • 看起来很适合使用 调试器
  • 编写代码时,先从简单但完美运行的东西开始,然后一点一点地增加复杂性,每一步都进行测试; 永远不要添加不起作用的代码。

标签: c++ function class parameter-passing


【解决方案1】:

老兄,注意while语句的条件,行

!(stock >= 1000 || stock <= 9999)

当 stock = 0 时返回真(在这种情况下总是真),所以程序不会进入循环。 也许你的意思是:

!(stock >= 1000 && stock <= 9999)

AND(&&) 不是 OR(||)

【讨论】:

  • 是的,我注意到了这一点并且已经改变了,谢谢。我的循环也不正确,所以我将其更改为 do-while 循环,现在它可以完美运行。我只需要对我的其他输入使用 do-while 来只接受正值
猜你喜欢
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多