我已经正确编译并运行了我的程序,但似乎变量 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;
}
主文件
#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;
}
自动售货机.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..??