变量不通过引用传递

时间:2013-08-22 14:44:25

标签: c++

我已正确编译并运行我的程序,但似乎变量sum不是通过引用传递的,它仍然是0。这里的任何帮助都是代码。

#include "VendingMachine.h"

int VendingMachine::MakeSelection(int ItemPrice[], int NumItems[],int &sum){

    int total_cost = 0;

    cout << "Enter your choice: ";
    cin >> choice;

    if(choice >= 1 && choice <= 9){
        while (choice != 0){
            NumItems[(choice-1) % 10]--;
            total_cost += ItemPrice[(choice-1)%10];
            choice/=10;

        }
    }
        sum = total_cost;
        return sum;
}

Main.cpp的

#include "VendingMachine.h"

int main()
{
    int Denominations = 5;

    int Coins[] = {100, 50, 20, 10, 5};
    int NumCoins[] = {10, 10, 10, 10, 10}; //assume we have 10 coins of each denomination

    const int Items = 9;
    int sum, deposit;

    int ItemPrice[ ] = { 75, 120, 120, 100, 150, 95, 110, 50, 120 }; //price in cents
    int  NumItems[ ] = { 10, 10, 10, 10, 10, 10, 10, 10, 10 }; 

    VendingMachine caller;

    caller.ShowMenu();
    cout << endl;

    cout << "Enter your money: ";
    cin >> deposit;

    caller.MakeSelection(ItemPrice,NumItems,sum);
    cout <<"The total cost is " << sum << endl;

    system("PAUSE");
    return 0;
}

Vending.h

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

using namespace std;

int total_cost;
int Coins[5];
int NumCoins[5];
int ItemPrice[9];
int NumItems[9];

class VendingMachine{
public:
    int MakeSelection(int ItemPrice[], int NumItems[],int &sum);
    void ReturnChange(int& input,int& sum, int Coins[],int NumCoins[]);
    void ShowMenu();
    void DisplayErrorMessage(int error);
    void PrintConfidentialInformation(int Denominations, int Items, int Coins[], int NumCoins[], int ItemPrice[] , int NumItems[]);
private:
    int choice;
    string Password;
    int deposit2;
};

总成本应该在MakeSelection cpp中返回sum值,但仍然会返回0 .. ??

3 个答案:

答案 0 :(得分:1)

MakeSelection根本不使用变量sum。

答案 1 :(得分:0)

你永远不会实际使用sum,因此值为0

答案 2 :(得分:0)

您的sum变量未被使用且您的MakeSelection来电未返回任何值。