Переменные не обновляются - PullRequest
0 голосов
/ 27 апреля 2018

Я создал эту программу для торговых точек, в которой жестко заданы три позиции, а переменные a_book, a_bat и a_hat не обновляются при вводе количеств. Почему?

#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <cstdlib>

using namespace std;

int main(void)
{


    int selectionMain;

    int selection;

    int a_book;
    int a_bat;
    int a_hat;






    cout << "\n\nHello, welcome to mIke's Convenience! How may I help you?" << endl;

    printf("\n\n\n");

    cout << "1. add products\n\n" << endl;
    cout << "2. remove products\n\n" << endl;
    cout << "3. procede to receipt\n\n\n" << endl;
    cout << "4. exit\n\n\n" << endl;


    printf("Please make a selection: ");
    scanf(" %d", &selectionMain);

    printf("\n\n\n");


    if(selectionMain == 1){



            cout << "You have selected 1.\n\n\n" << endl;

            cout << "1. book  -  $5.00 ea\n\n" << endl;
            cout << "2. baseball bat  -  $11.00 ea\n\n" << endl;
            cout << "3. hat  -  $7.00 ea\n\n\n" << endl;


            printf("please select a product to add by typing a number (1, 2, 3): ");
            scanf(" %d", &selection);

            if(selectionMain == 1){


                    printf("select desired quantity of books to add: ");
                    scanf(" %d", &a_book);

                }else if(selectionMain == 2){

                    printf("select desired quantity of baseball bats to add: ");
                    scanf(" %d", &a_bat);

                }else{

                    printf("select desired quantity of hats to add: ");
                    scanf(" %d", &a_hat);

        }



            return main();





        }else if(selectionMain == 2){

            cout << "You have selected 2.\n\n\n" << endl;

            cout << "1. book  -  $5.00 ea\n\n" << endl;
            cout << "2. baseball bat  -  $11.00 ea\n\n" << endl;
            cout << "3. hat  -  $7.00 ea\n\n\n" << endl;


            printf("please select a product to remove by typing a number (1, 2, 3): ");
            scanf(" %d", &selectionMain);

            return main();





        }else if(selectionMain == 3){

            cout << "You have selected 3.\n\n\n" << endl;
            cout << "-------your receipt-------\n\n\n" << endl;


            printf("book(s) x %d!\n", a_book);


            printf("baseball bat(s) x %d!\n", a_bat);


            printf("hat(s) x %d!\n\n", a_hat);



            cout << "-----Thank you for shopping at mIke's Convenience. Please play responsibly?-----\n\n\n" << endl;

            printf("press any letter key and then 'Enter' to return to main screen ");
            scanf(" %d", &selectionMain);

            return main();





        }else{
            void exit();
        }




    return 0;
}

Ответы [ 3 ]

0 голосов
/ 27 апреля 2018

Переменным присваивается только если selectionMain = 1.

Печатается, если selectionMain = 3.

Тем не менее, вы всегда звоните main() снова и снова через return main(), что определяет другой набор:

int a_book;
int a_bat;
int a_hat;

который неинициализирован .

Таким образом, ранее введенные значения для упомянутых переменных «теряются» в локальной области .

0 голосов
/ 27 апреля 2018

Надеюсь, это поможет.

while(true)  // enclose your if-else statements with in a loop
{
    // ...

    if(selectionMain == 1)
    {
        //...
    }
    else if(selectionMain == 2)
    {
        // ...
        //return main();        // remove this line
    }
    else if(selectionMain == 3)
    {
        // ...
        scanf(" %d", &selectionMain);
        //return main();    // remove this line, so that the variables will not be re-setted
    }
    else
        break;      // break out of the loop.
}
return 0;
0 голосов
/ 27 апреля 2018

Основная причина в том, что вы сделали рекурсивный вызов main после каждой опции. Каждый раз, когда выполняется рекурсивный вызов, каждый вызов будет иметь свой собственный набор значений для трех переменных. Вы можете решить эту проблему, добавив цикл while и выполняя его до тех пор, пока пользователь не введет 4.

#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <cstdlib>
using namespace std;

int main(void) {

int selectionMain;

int selection;

int a_book=0;
int a_bat=0;
int a_hat=0;

cout << "\n\nHello, welcome to mIke's Convenience! How may I help you?" << endl;
while(1)
{
cout << "1. add products\n\n" << endl;
cout << "2. remove products\n\n" << endl;
cout << "3. procede to receipt\n\n" << endl;
cout << "4. exit\n\n" << endl;
cout<<"Please make a selection: ";

cin>>selectionMain;


if(selectionMain == 1){



        cout << "You have selected 1.\n\n\n" << endl;

        cout << "1. book  -  $5.00 ea\n\n" << endl;
        cout << "2. baseball bat  -  $11.00 ea\n\n" << endl;
        cout << "3. hat  -  $7.00 ea\n\n\n" << endl;


        cout<<"please select a product to add by typing a number (1, 2, 3): ";
        cin>>selection;

    if(selection == 1){
                cout<<"select desired quantity of books to add: ";
                int temp;
                cin>>temp;
                a_book+=temp;

            }else if(selection == 2){

                cout<<"select desired quantity of baseball bat to add: ";
                int temp;
                cin>>temp;
                a_bat+=temp;

            }else{

                cout<<"select desired quantity of hats to add: ";
                int temp;
                cin>>temp;
                a_hat+=temp;
    }

    }else if(selectionMain == 2){

        cout << "You have selected 2.\n\n\n" << endl;

        cout << "1. book  -  $5.00 ea\n\n" << endl;
        cout << "2. baseball bat  -  $11.00 ea\n\n" << endl;
        cout << "3. hat  -  $7.00 ea\n\n\n" << endl;

        cin>>selection;
        //Same logic as addition
        continue;

    }else if(selectionMain == 3){

        cout << "You have selected 3.\n\n\n" << endl;
        cout << "-------your receipt-------\n\n\n" << endl;


        printf("book(s) x %d!\n", a_book);


        printf("baseball bat(s) x %d!\n", a_bat);


        printf("hat(s) x %d!\n\n", a_hat);



        cout << "-----Thank you for shopping at mIke's Convenience. Please play responsibly?-----\n\n\n" << endl;

        printf("press any letter key and then 'Enter' to return to main screen ");
        scanf(" %d", &selectionMain);
        continue;
    }
    else
        break;

}
return 0;
}

Редактировать:

Также, если вы действительно хотите обновить, вы не должны перезаписывать одну и ту же переменную. Должно быть

int temp;
scanf("%d",temp);
a_book+=temp;

и то же самое касается удаления. Вы должны сделать это для всех трех переменных.

Редактировать 2: Почему вы использовали и cout, и printf? Это создаст ошибку. Либо просто используйте cout и cin, либо используйте только printf и scanf.

...