Суммирование элементов из скопированного массива в c ++ - PullRequest
0 голосов
/ 21 апреля 2020

Я написал программу, которая создает меню ресторана через текстовый файл, открывается в другой программе и используется для создания заказа клиента.

У меня есть функция, которая необходима для создания общей суммы в конце, однако общая сумма никогда не создается, вместо этого программа выдает сумму из itemPrice * itemQuantity и печатает ее вместо суммирования итоговой суммы.

У меня есть элементы, сохраненные в массиве menuItem, и я пытаюсь скопировать их в массив billingItems для параллельного суммирования цен. Какой шаг мне не хватает, чтобы total суммировал цены, поэтому total внизу будет равно 44 (16 + 28)?

Спасибо

Создание заказа в main ():

int main(){
    int i;
    Item billingItem[MAX_ORDER];
    Item menuItem[MAX_ORDER];
    int itemNumber;
    int itemQuantity;
    int billOpt;

    std::ofstream transactionFile;
    transactionFile.open("transactionFile.txt");
    int count = 0;

    for(i = 0; i < MAX_ORDER; i++) {
        std::cout << "Item number: ";
        std::cin >> itemNumber;
        i = itemNumber - 1;
        std::cout << "Quantity: ";
        std::cin >> itemQuantity;
        menuItem[i].saveItemDetails(transactionFile);

        std::cout << "\nWould you like to add another item?" << std::endl;
        std::cout << "1. Yes\n2. No" << std::endl;
        std::cin >> billOpt;
        if (billOpt <= 0 | billOpt > 2) {
            std::cout << "Error. Please enter a valid number: ";
            std::cin >> billOpt;
        }
        if(billOpt == 2) { break; }
    }
    billingItem[i] = menuItem[i];
    billingItem[i].calculateVAT(count, itemQuantity);

    transactionFile.close();

функция в файле реализации:

void Item::calculateVAT(int count, int itemQuantity){
double total = 0.0;
double newItemPrice;

newItemPrice = itemPrice * itemQuantity;
total = newItemPrice + total;


//extra couts to see what is happening
std::cout << "ITEM QUANTITY" << itemQuantity <<"\n";
std::cout << "TOTAL" << total <<"\n";
}

что выдается при запуске программы:

Item: 2| Category: Meat| Description: Pork Chops| Price: £8
COUNT3
ITEM QUANTITY2
TOTAL16
Item: 3| Category: Meat| Description: Ribs| Price: £14
COUNT4
ITEM QUANTITY2
TOTAL28

1 Ответ

1 голос
/ 21 апреля 2020

Вы можете объявить total как stati c в функции, поэтому она инициализируется только один раз.

 void Item::calculateVAT(int count, int itemQuantity){
static double total = 0.0;
double newItemPrice;

newItemPrice = itemPrice * itemQuantity;
total += newItemPrice ; // 


//extra couts to see what is happening
std::cout << "ITEM QUANTITY" << itemQuantity <<"\n";
std::cout << "TOTAL" << total <<"\n";
}

Другим решением было бы объявить итоговую переменную в main и изменить сигнатуру вашей функции. Это будет означать печать итогов с вашего основного.

Функция calcVAT:

double Item::calculateVAT(int count, int itemQuantity)// No more void
{  
double total = 0.0; // this one only serves in the function scope
double newItemPrice;

newItemPrice = itemPrice * itemQuantity;
total = newItemPrice + total;


//extra couts to see what is happening
std::cout << "ITEM QUANTITY" << itemQuantity <<"\n";
std::cout << "TOTAL" << total <<"\n";

return total; // this number will add up in the main
}

Ваш основной:

int main(){
    int i;
    Item billingItem[MAX_ORDER];
    Item menuItem[MAX_ORDER];
    int itemNumber;
    int itemQuantity;
    int billOpt;
    double total = 0.0; // this here will serve as the sum of all your items prices

    std::ofstream transactionFile;
    transactionFile.open("transactionFile.txt");
    int count = 0;

    for(i = 0; i < MAX_ORDER; i++) {
        std::cout << "Item number: ";
        std::cin >> itemNumber;
        i = itemNumber - 1;
        std::cout << "Quantity: ";
        std::cin >> itemQuantity;
        menuItem[i].saveItemDetails(transactionFile);

        std::cout << "\nWould you like to add another item?" << std::endl;
        std::cout << "1. Yes\n2. No" << std::endl;
        std::cin >> billOpt;
        if (billOpt <= 0 | billOpt > 2) {
            std::cout << "Error. Please enter a valid number: ";
            std::cin >> billOpt;
        }
        if(billOpt == 2) { break; }
    }
    billingItem[i] = menuItem[i];
   total +=  billingItem[i].calculateVAT(count, itemQuantity); // modified here``
   std::cout << "TOTAL" << total << std::endl;


    transactionFile.close();

Для справки, я сделал простой код с basi c ситуация:

     void calculateVAT(int count, int itemQuantity) { // Static version, is initialized only once and then only gets updated

    static double total = 0;
    double newItemPrice;

    newItemPrice = 10 * itemQuantity;
    total += newItemPrice ;


    //extra couts to see what is happening
    std::cout << "ITEM QUANTITY " << itemQuantity << "\n";
    std::cout << "TOTAL from function  " << total << "\n";
}

double d_calculateVAT(int count, int itemQuantity) { // Non void version, returns a sum to a variable in the main

    double sum = 0;
    double newItemPrice;

    newItemPrice = 10 * itemQuantity;
    sum += newItemPrice;

    return sum;
}

int main()
{
    int itemQty = 5;
    double sum = 0; // if you want to call it from the main

    calculateVAT(0, 4); // void version with static - will update its total variable as 40
    calculateVAT(0, 7); // void version with static - will update its total variable as 40 + 70 = 110

    sum+=d_calculateVAT(0, 4); // double version - will return sum = 40
    sum+=d_calculateVAT(2, 7); // double version - will return sum + 70 = 110

    std::cout << "TOTAL from main " << sum << std::endl;

    while (1)
    { }

    return 0;
}

Также, может быть, это для другой цели, но я не вижу точки переменной "count", отправляемой в CalculateVAT, она не используется в функции.

...