Торговый автомат C ++ - Ошибка в цикле while - PullRequest
0 голосов
/ 02 августа 2020

Я пишу код «торговый автомат / покупка продуктов» на C ++, где у меня есть меню из 5 пунктов, и пользователь может добавлять их в качестве моих элементов по своему усмотрению. Цена рассчитывается в конце.

Поскольку пользователь может добавлять столько товаров, сколько хочет, я использовал while l oop, чтобы они могли «продолжить покупки». Однако мне не удалось это сделать, потому что код продолжал работать. Я попытался вставить оператор switch в функцию, но не вызвал «ответ» должным образом. int shoppingCart(). Если бы кто-нибудь мог помочь мне с абстрагированием этого кода, было бы здорово!)

Код ниже (это оригинал, я поместил отредактированный ниже):

#include <iostream>
using namespace std;


void vendingMachine() {
  cout << "1. Popcorn: $2" << endl;
  cout << "2. Coconut Clusters: $3" << endl;
  cout << "3. Granola Bar: $2.50" << endl;
  cout << "4. Trail Mix: $1.50" << endl;
  cout << "5. Chocolate: $1" << endl;
  cout << "Press 0 to checkout" << endl;
}

int main() {
  cout << "Vending Machine" << endl;
  cout << "----Items------" << endl;

  vendingMachine();

  
  cout << "Enter you selection: " << flush;
  int input;
  cin >> input;
  float cost;

  switch (input) {
  case 1:
    cout << "You added Popcorn to your cart." << endl;
    cost = 2;
    break;
  case 2:
    cout << "You added Coconut Clusters to your cart." << endl;
    cost = 3;
    break;
  case 3:
    cout << "You added Granola Bar to your cart." << endl;
    cost = 2.50;
    break;
  case 4:
    cout << "You added Trail Mix to your cart." << endl;
    cost = 1.50;
    break;
  case 5:
    cout << "You added Chocolate to your cart." << endl;
    cost = 1;
    break;
  case 6:
    cout << "Checkout" << endl;
    break;
  default:
    cout << "Please select an item from the menu" << endl;
  }
  cout << "Continue shopping (y/n): " << flush;
  string reply;
  cin >> reply;


  while(reply == "y") {
    cout << "Enter your selection: " << flush;
    int input;
    cin >> input;
    float cost;

    switch (input) {
    case 1:
      cout << "You added Popcorn to your cart." << endl;
      cost = 2;
      break;
    case 2:
      cout << "You added Coconut Clusters to your cart." << endl;
      cost = 3;
      break;
    case 3:
      cout << "You added Granola Bar to your cart." << endl;
      cost = 2.50;
      break;
    case 4:
      cout << "You added Trail Mix to your cart." << endl;
      cost = 1.50;
      break;
    case 5:
      cout << "You added Chocolate to your cart." << endl;
      cost = 1;
      break;
    case 6:
      cout << "Checkout" << endl;
      break;
    default:
      cout << "Please select an item from the menu" << endl;
    }
    cout << "Continue shopping (y/n): " << flush;
    string reply;
    cin >> reply;
    break;
  }
  cout << "Proceding to checkout..." << endl;
  



  

  cout << "Pay amount: $" << flush;
  float money;
  cin >> money;

  if (money > cost) {
    float change = money-cost;
    cout << "Thank you! You have $" << change << " change." << endl;
  }

  if (money == cost) {
    cout << "Thank you! Have a nice day!." << endl;
  }

  if (money < cost) {
    float amountOwed = cost-money;
    cout << "Please insert another $" << amountOwed << endl;

    cout << "Enter amount: " << flush;
    float payment;
    cin >> payment;

    if (payment > amountOwed) {
    float change2 = payment-cost;
    cout << "Thank you! You have $" << change2 << " change." << endl;
    }

    if (payment == amountOwed) {
      cout << "Thank you! Have a nice day!." << endl;
    }

    if (payment < amountOwed) {
      cout << "Sorry, you did not enter enough money. Your cart has emptied." << endl;
    }

  }
  return 0;
}

Отредактированный код:

#include <iostream>
using namespace std;


void vendingMachine() {
  cout << "1. Popcorn: $2" << endl;
  cout << "2. Coconut Clusters: $3" << endl;
  cout << "3. Granola Bar: $2.50" << endl;
  cout << "4. Trail Mix: $1.50" << endl;
  cout << "5. Chocolate: $1" << endl;
  cout << "Press 0 to checkout" << endl;
}

int processSelection() {
  cout << "Enter your selection: " << flush;
  int input;
  cin >> input;
  
  return input;
}

int shoppingCart() {
  int selection = processSelection();
  float cost;
  switch (selection) {
  case 1:
    cout << "You added Popcorn to your cart." << endl;
    cost = 2;
    break;
  case 2:
    cout << "You added Coconut Clusters to your cart." << endl;
    cost = 3;
    break;
  case 3:
    cout << "You added Granola Bar to your cart." << endl;
    cost = 2.50;
    break;
  case 4:
    cout << "You added Trail Mix to your cart." << endl;
    cost = 1.50;
    break;
  case 5:
    cout << "You added Chocolate to your cart." << endl;
    cost = 1;
    break;
  case 6:
    cout << "Checkout" << endl;
    break;
  default:
    cout << "Please select an item from the menu" << endl;
  }
  cout << "Continue shopping (y/n): " << flush;
  string reply;
  cin >> reply;

  return reply;
}

int main() {
  cout << "Vending Machine" << endl;
  cout << "----Items------" << endl;

  vendingMachine();

  int reply = shoppingCart();

  float cost;
  

  


  while(reply == "y") {
    processSelection();

    shoppingCart();
  }
  cout << "Proceding to checkout..." << endl;
  



  

  cout << "Pay amount: $" << flush;
  float money;
  cin >> money;

  if (money > cost) {
    float change = money-cost;
    cout << "Thank you! You have $" << change << " change." << endl;
  }

  if (money == cost) {
    cout << "Thank you! Have a nice day!." << endl;
  }

  if (money < cost) {
    float amountOwed = cost-money;
    cout << "Please insert another $" << amountOwed << endl;

    cout << "Enter amount: " << flush;
    float payment;
    cin >> payment;

    if (payment > amountOwed) {
    float change2 = payment-cost;
    cout << "Thank you! You have $" << change2 << " change." << endl;
    }

    if (payment == amountOwed) {
      cout << "Thank you! Have a nice day!." << endl;
    }

    if (payment < amountOwed) {
      cout << "Sorry, you did not enter enough money. Your cart has emptied." << endl;
    }

  }
  return 0;
}

1 Ответ

4 голосов
/ 02 августа 2020

Похоже, вы очень хорошо учитесь программировать. Некоторые мысли:

  1. Абстрактный дублирующий код. Ваш оператор switch идентичен в двух местах. Это упрощает появление ошибок! Например, если цена одного предмета изменится, вы можете забыть обновить его в одном месте, но не в другом, что может привести к сложным ошибкам.
  2. У вас есть инструкция break в конце а l oop. Вы хотите останавливаться на каждой итерации? Возможно нет. Когда делать вы хотите вырваться из l oop? При каких условиях вы не хотите продолжать? Подумайте о потоке управления и о том, как работают циклы while. Пока выполняется какое-то условие, продолжайте цикл. Как только он окажется ложным, прекратите зацикливаться. Что это за состояние? Это просто reply == y? Это работает на первой итерации, а как насчет других итераций?
  3. Некоторые из вас, если в операторах if говорят что-то вроде «хорошего дня». Для меня это звучит как хорошее время, чтобы вырваться из l oop. Как вы думаете?
...