2015-05-21 5 views
0

Я работаю над проектом для класса, и я почти полностью выполнил весь свой код. У меня только одна проблема (THE CODE IS IN C++). Я не слишком хорошо использую логические функции, особенно в случае для этой программы. Если бы вы, ребята, могли помочь мне написать или подтолкнуть меня в правильном направлении для этого кода, я был бы признателен. Эта программа должна быть программой Soda Machine, созданной из структур. Мой вопрос заключается в том, как передать массив функции boolean, чтобы проверить, есть ли какие-либо напитки, оставшиеся для тех, которые клиент хочет приобрести. Если напиток не останется, программа распечатает «Извините, мы проданы. Сделайте еще один выбор». Если есть еще доступные напитки, просто ничего не делайте и продолжайте с программой. Это в значительной степени подтвердит количество оставшихся напитков. Я попытался написать функцию, но я не уверен, что это правильно, я отправлю ее вам, чтобы вы посмотрели на нее. Если вам нужна какая-либо другая информация, пожалуйста, дайте мне знать. Спасибо за помощь перед парнями.Передача массива в логическую функцию

#include <iostream> 
#include <string> 
#include <cmath> 
#include <iomanip> 

using namespace std; 

struct Machine 
{ 
    string name; 

    double cost; 

    int drinks; 
}; 

int displayMenu(int choice); 

double inputValidation(double); 

bool drinksRemaining(); // this is the function that will check if there are any drinks of the choice left 

int displayMenu(int choice) 
{ 

    cout << "SOFT DRINK MACHINE\n"; 

    cout << "------------------\n"; 

    cout << "1) Cola ($0.65)\n"; 

    cout << "2) Root Beer ($0.70)\n"; 

    cout << "3) Lemon-Lime ($0.75)\n"; 

    cout << "4) Grape Soda ($0.85)\n"; 

    cout << "5) Water ($0.90)\n"; 

    cout << "6) Quit Program\n"; 

    cout << endl; 

    cout << "Please make a selection: "; 

    cin >> choice; 

    return choice; 

} 

double inputValidation(double amount) 
{ 

    while (amount < 0.00 || amount > 1.00) 
    { 
     cout << "Please enter an amount between $0.00 and $1.00.\n"; 

     cout << "It should also be equal to or greater than the drink price : \n"; 

     cin >> amount; 
    } 

    return amount; 

} 

bool drinksRemaining() // this is the function that I am having trouble with 
{ 
    if (drinks <= 0) 
    { 
     cout << "Sorry we are out of this drink. Please choose another one."; 

     cin >> drinkChoice; 

     return true; 
    } 

    else 
    { 
     return false; 
    } 
} 


int main() 
{ 
    const int DRINK_NUMS = 5; 

    int selection = 0; 

    double amountInserted = 0.00; 

    double changeReturned = 0.00; 

    double profit = 0.00; 

    Machine drink[DRINK_NUMS] = { { "Cola", .65, 20 }, { "Root Beer", .70, 20 }, { "Lemon-Lime", .75, 20 }, { "Grape Soda", .85, 20 }, { "Water", .90, 20 } }; 

    do 
    { 
     profit += amountInserted - changeReturned; 

     selection = displayMenu(selection); 

     if (selection == 1) 
     { 
     cout << "Please enter the amount you want to insert:\n"; 

     cin >> amountInserted; 

     inputValidation(amountInserted); 

     changeReturned = amountInserted - drink[0].cost; 

     cout << setprecision(2) << fixed << "CHANGE : $" << changeReturned << endl; 

     drink[0].drinks--; 

     } 

     else if (selection == 2) 
     { 
     cout << "Please enter the amount you want to insert:\n"; 

     cin >> amountInserted; 

     inputValidation(amountInserted); 

     changeReturned = amountInserted - drink[1].cost; 

     cout << setprecision(2) << fixed << "CHANGE : $" << changeReturned << endl; 

     drink[1].drinks--; 

     } 

     else if (selection == 3) 
     { 
     cout << "Please enter the amount you want to insert.\n"; 

     cin >> amountInserted; 

     changeReturned = amountInserted - drink[2].cost; 

     cout << setprecision(2) << fixed << "CHANGE : $" << changeReturned << endl; 

     drink[2].drinks--; 


     } 

     else if (selection == 4) 
     { 
     cout << "Please enter the amount you want to insert.\n"; 

     cin >> amountInserted; 

     changeReturned = amountInserted - drink[3].cost; 

     cout << setprecision(2) << fixed << "CHANGE : $" << changeReturned << endl; 

     drink[3].drinks--; 

     } 

     else if (selection == 5) 
     { 
     cout << "Please enter the amount you want to insert.\n"; 

     cin >> amountInserted; 

     changeReturned = amountInserted - drink[4].cost; 

     cout << setprecision(2) << fixed << "CHANGE : $" << changeReturned << endl; 

     drink[4].drinks--; 

     } 

     else if (selection == 6) 
     { 
     cout << endl; 

     cout << "SOFT DRINK MACHINE REPORT\n"; 

     cout << "--------------------------\n"; 

     cout << "Total amount earned: $" << profit << endl; 

     cout << endl; 
     } 

     else 
     { 
     cout << "Invalid selection. Please try again."; 

     displayMenu(selection); 
     } 

    }while (selection != 6); 

    system("PAUSE"); 

    return 0; 
} 
+0

вы можете использовать 'зОго :: array' вместо массива с стилем ? – dwcanillas

+0

Функция будет выглядеть примерно так: 'bool drinksRemaining (std :: array current_machine)' и там вы ссылаетесь на 'current_machine [whatever_the_product_number_is]'. Вы можете улучшить это дальше с помощью typedef или с использованием другой структуры данных, но это упражнение для читателя;) – shuttle87

ответ

2

Функция необходим объект или ссылку на объект типа Machine.

bool drinksRemaining(Machine const& m); 

и может быть реализован очень просто:

bool drinksRemaining(Machine const& m) 
{ 
    return (m.drinks > 0); 
} 

Вы можете использовать его как:

if (selection == 1) 
    { 
    if (drinksRemaining(drink[0])) 
    { 
     cout << "Please enter the amount you want to insert:\n"; 

     cin >> amountInserted; 

     inputValidation(amountInserted); 

     changeReturned = amountInserted - drink[0].cost; 

     cout << setprecision(2) << fixed << "CHANGE : $" << changeReturned << endl; 

     drink[0].drinks--; 
    } 
    else 
    { 
     cout << "Sorry we are out of this drink. Please choose another one."; 
    } 
    } 
+0

Отлично работает! –

Смежные вопросы