Как правильно подсчитать пользовательские входы, используя операторы if-then в C ++ - PullRequest
1 голос
/ 11 июля 2019

Я пытаюсь написать программу для домашнего задания, которая, помимо прочего, отслеживает количество определенных видов закусок, которые приобретаются во время посещения кинотеатра.Сначала он представляет пользователю список переменных предметов и должен отображать номер каждого приобретенного предмета после того, как пользователь завершит ввод приобретенных предметов.Хотя мой код компилируется, покупаемое количество большинства элементов, отображаемых программой, не совпадает с тем, что я надеюсь увидеть на основе моих входных данных.

Я не уверен, как изменить код для решения этой проблемыПо какой-то причине значение переменной softDrink, похоже, сохраняется и отображается, но это не относится ни к одной из других переменных.

#include <iostream>

using namespace std;

int main()
{
//Declare the mathematical variables
int age = 0, average = 0, youngest = 0, oldest = 0, sum = 0, counter = 0;
//Declare the age variables
int ageGroup1 = 0, ageGroup2 = 0, ageGroup3 = 0, ageGroup4 = 0, ageGroup5 
= 0;
//Declare the snack variables
int snack = 0, softDrink = 0, popcorn = 0, nachos = 0, softPop = 0, 
softNachos = 0, organic = 0;

//Display the menu
cout << "==========================" << endl;
cout << "  THEATER STATS PROGRAM" << endl;
cout << "==========================\n" << endl;
cout << "Movie theater snacks available for purchase" << endl;
cout << "==========================================" << endl;
cout << "1 - Soft Drink (such as Coca Cola, ICCEE, Mineral Water etc...)" 
<< endl;
cout << "2 - Popcorn" << endl;
cout << "3 - Nachos" << endl;
cout << "4 - Soft drink & Popcorn" << endl;
cout << "5 - Soft drink & Nachos" << endl;
cout << "6 - Organic and Gluten-free snacks" << endl;
cout << "7 - None" << endl;
cout << "==========================================" << endl;

//Prompt a series of inputs to determine how many attendees fall into 
each age group and what snacks they will buy
cout << "Enter age of attendee (-1 to quit): ";
cin >> age;

while (age != -1)
{
    //Prompt user input for the purchased snacks
    cout << "Movie theater snack purchased. (Select items 1 - 7): ";
    cin >> snack;

    //Keep track of youngest and oldest attendees
    if (age < youngest)
        youngest = age;
    if (age > oldest)
        oldest = age;

    //Sum up all the inputted ages
    sum = sum + age;
    counter++;

    //Store the values for age inputs into different groups
    if (age >= 0 && age <= 18)
         ageGroup1++;
    else if (age >= 19 && age <= 30)
        ageGroup2++;
    else if (age >= 31 && age <= 40)
        ageGroup3++;
    else if(age >= 41 && age <= 60)
        ageGroup4++;
    else if (age >= 61)
        ageGroup5++;

    //Store the values for snack inputs
    if (snack == 1 || snack == 4 || snack == 5)
        softDrink++;
    else if (snack == 2 || snack == 4)
        popcorn++;
    else if (snack == 3 || snack == 5)
        nachos++;
    else if (snack == 4)
        softPop++;
    else if (snack == 5)
        softNachos++;
    else if (snack == 6)
        organic++;
    //Inform the user when they have inputted an invalid snack value
    while (snack < 1 || snack > 7)
    {
            cout << "Invalid selection, please choose from 1 - 7." << 
            endl;
            cout << "Movie theater snack purchased. (Select items 1 - 7): 
            ";
            cin >> snack;
    }

    //Prompt the user to continue entering age values and keep track of 
    the number of inputted ages
    cout << "Enter age of attendee (-1 to quit): ";
    cin >> age;
    counter++;
}

//Calculate the average age of the attendees
average = sum / (counter - 2);

//Display the results of the user's inputs
cout << "==================================" << endl;
cout << "  THEATER STATS PROGRAM RESULTS" << endl;
cout << "==================================\n" << endl;
cout << "Age 0  to 18:    " << ageGroup1 << endl;
cout << "Age 19 to 30:    " << ageGroup2 << endl;
cout << "Age 31 to 40:    " << ageGroup3 << endl;
cout << "Age 41 to 60:    " << ageGroup4 << endl;
cout << "Over 60:         " << ageGroup5 << "\n" << endl;
cout << "The average age was " << average << endl;
cout << "The youngest person in attendance was " << youngest << endl;
cout << "The oldest person in attendance was " << oldest << endl;
cout << "\nTheater Concession Stand sales" << endl;
cout << "==================================" << endl;
cout << "Soft Drink (such as Coca Cola, ICCEE, Mineral Water etc.): " << 
softDrink << endl;
cout << "Popcorn: " << popcorn << endl;
cout << "Nachos: " << nachos << endl;
cout << "Soft Drink & Popcorn: " << softPop << endl;
cout << "Soft Drink & Nachos: " << softNachos << endl;
cout << "Organic and Gluten-free snacks: " << organic << endl;

return 0;
}

В своем текущем состоянии этот код компилируется без каких-либоошибки, несмотря на то, что они не работают должным образом.

1 Ответ

0 голосов
/ 11 июля 2019

После получения возраста инициализируйте самый старый и самый младший возраст. Также я удалил операторы else if, как рекомендовал @Nico Schertler.

    cin >> age;
    youngest = age;
    oldest = age;

    while (age != -1)
    {
        //Prompt user input for the purchased snacks
        cout << "Movie theater snack purchased. (Select items 1 - 7): ";
        cin >> snack;

        //Keep track of youngest and oldest attendees
        if (age < youngest)
            youngest = age;
        if (age > oldest)
            oldest = age;

        //Sum up all the inputted ages
        sum = sum + age;
        counter++;

        //Store the values for age inputs into different groups
        if (age >= 0 && age <= 18)
            ageGroup1++;
        if (age >= 19 && age <= 30)
            ageGroup2++;
        if (age >= 31 && age <= 40)
            ageGroup3++;
        if (age >= 41 && age <= 60)
            ageGroup4++;
        if (age >= 61)
            ageGroup5++;

        //Store the values for snack inputs
        if (snack == 1 || snack == 4 || snack == 5)
            softDrink++;
        if (snack == 2 || snack == 4)
            popcorn++;
        if (snack == 3 || snack == 5)
            nachos++;
        if (snack == 4)
            softPop++;
        if (snack == 5)
            softNachos++;
        if (snack == 6)
            organic++;
        //Inform the user when they have inputted an invalid snack value
        while (snack < 1 || snack > 7)
        {
            cout << "Invalid selection, please choose from 1 - 7." <<
                endl;
            cout << "Movie theater snack purchased. (Select items 1 - 7): ";
                cin >> snack;
        }

        //Prompt the user to continue entering age values and keep track of 
    /*  the number of inputted ages*/
            cout << "Enter age of attendee (-1 to quit): ";
        cin >> age;
        counter++;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...