2013-08-22 2 views
-6

내 프로그램을 올바르게 컴파일하고 실행했지만 변수 합계가 참조로 전달되지 않고 여전히 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의 합계의 값을 반환해야하지만 여전히 0을 반환 .. ??

+4

'sum'은 사용되지 않습니다. 그것에 대한 경고가 있습니다. – chris

+0

함수에 반환 값이 없으므로 정의되지 않은 동작이 발생합니다. – 0x499602D2

+0

컴파일러에서 일부 플래그를 활성화해야합니다 ... – nouney

답변

1

MakeSelection은 변수 합계를 전혀 사용하지 않습니다.

0

당신은 실제로 합계를 사용하지 않습니다, 따라서 값은 0

+1

실제로 변수는 초기화되지 않습니다. –

0

귀하의 sum 변수를 사용하지 않을 당신의 MakeSelection 호출 값을 반환하지 않습니다이다.

관련 문제